Merge pull request #5322 from RoscoeLotriet/stream-foreach-ifelse-logic

BAEL-2252 Stream foreach ifelse logic
This commit is contained in:
Tom Hombergs 2018-10-01 21:22:56 +02:00 committed by GitHub
commit 5aa8a5c985
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1,41 @@
package com.baeldung.stream.conditional;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
public class StreamForEachIfElseUnitTest {
@Test
public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
ints.stream()
.forEach(i -> {
if (i.intValue() % 2 == 0) {
Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
} else {
Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
}
});
}
@Test
public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> evenIntegers = ints.stream()
.filter(i -> i.intValue() % 2 == 0);
Stream<Integer> oddIntegers = ints.stream()
.filter(i -> i.intValue() % 2 != 0);
evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
}
}