From 03ebc0255644c181da7bd56525185ea59f41d04f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 24 Sep 2016 11:33:47 +0200 Subject: [PATCH] Refactor Stream> example --- .../java9/Java9OptionalsStreamTest.java | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java index 336e803985..102ceda18f 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java @@ -13,36 +13,31 @@ import org.junit.Test; public class Java9OptionalsStreamTest { - private List> listOfOptionals; + private static List> 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 public void filterOutPresentOptionalsWithFilter() { assertEquals(4, listOfOptionals.size()); - //@format:off + List filteredList = listOfOptionals.stream() - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); - //@format:on + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); assertEquals("bar", filteredList.get(1)); } - + @Test public void filterOutPresentOptionalsWithFlatMap() { assertEquals(4, listOfOptionals.size()); - //@format:off + List filteredList = listOfOptionals.stream() - .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) - .collect(Collectors.toList()); - //@format:on + .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) + .collect(Collectors.toList()); assertEquals(2, filteredList.size()); + assertEquals("foo", filteredList.get(0)); assertEquals("bar", filteredList.get(1)); } @@ -50,11 +45,11 @@ public class Java9OptionalsStreamTest { @Test public void filterOutPresentOptionalsWithJava9() { assertEquals(4, listOfOptionals.size()); - //@format:off + List filteredList = listOfOptionals.stream() - .flatMap(Optional::stream) - .collect(Collectors.toList()); - //@format:on + .flatMap(Optional::stream) + .collect(Collectors.toList()); + assertEquals(2, filteredList.size()); assertEquals("foo", filteredList.get(0)); assertEquals("bar", filteredList.get(1));