Refactor Stream<Optional<?>> example

This commit is contained in:
Grzegorz Piwowarek 2016-09-24 11:33:47 +02:00
parent 3adfc4faaa
commit 03ebc02556
1 changed files with 15 additions and 20 deletions

View File

@ -13,22 +13,17 @@ import org.junit.Test;
public class Java9OptionalsStreamTest { public class Java9OptionalsStreamTest {
private List<Optional<String>> listOfOptionals; private static List<Optional<String>> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
@Before
public void populateStream() {
listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
}
@Test @Test
public void filterOutPresentOptionalsWithFilter() { public void filterOutPresentOptionalsWithFilter() {
assertEquals(4, listOfOptionals.size()); assertEquals(4, listOfOptionals.size());
//@format:off
List<String> filteredList = listOfOptionals.stream() List<String> filteredList = listOfOptionals.stream()
.filter(Optional::isPresent) .filter(Optional::isPresent)
.map(Optional::get) .map(Optional::get)
.collect(Collectors.toList()); .collect(Collectors.toList());
//@format:on
assertEquals(2, filteredList.size()); assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0)); assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1)); assertEquals("bar", filteredList.get(1));
@ -37,12 +32,12 @@ public class Java9OptionalsStreamTest {
@Test @Test
public void filterOutPresentOptionalsWithFlatMap() { public void filterOutPresentOptionalsWithFlatMap() {
assertEquals(4, listOfOptionals.size()); assertEquals(4, listOfOptionals.size());
//@format:off
List<String> filteredList = listOfOptionals.stream() List<String> filteredList = listOfOptionals.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList()); .collect(Collectors.toList());
//@format:on
assertEquals(2, filteredList.size()); assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0)); assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1)); assertEquals("bar", filteredList.get(1));
} }
@ -50,11 +45,11 @@ public class Java9OptionalsStreamTest {
@Test @Test
public void filterOutPresentOptionalsWithJava9() { public void filterOutPresentOptionalsWithJava9() {
assertEquals(4, listOfOptionals.size()); assertEquals(4, listOfOptionals.size());
//@format:off
List<String> filteredList = listOfOptionals.stream() List<String> filteredList = listOfOptionals.stream()
.flatMap(Optional::stream) .flatMap(Optional::stream)
.collect(Collectors.toList()); .collect(Collectors.toList());
//@format:on
assertEquals(2, filteredList.size()); assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0)); assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1)); assertEquals("bar", filteredList.get(1));