Skip to content

Commit b7b1693

Browse files
TSobalapivovarit
authored andcommitted
[BAEL-872] map and flatMap difference (eugenp#1892)
* injecting beans * XML-based configuration replaced with Java Config. * [BAEL-431] Exploring TestRestTemplate. * Revert of evaluation task "XML-based configuration replaced with Java Config." This reverts commit 66471cf. * Revert of evaluation task "injecting beans" This reverts commit d2ac201. * [BAEL-431] fix to the tests in TestRestTemplateBasicLiveTest. * [BAEL-431] added more meaningful user and password for auth. * [BAEL-820] examples of wait() and sleep() methods. * [BAEL-820] wait() and sleep() examples. * [BAEL-829] number of occurences of a char in a String. * [BAEL-829] printlns changed to assertions. * [BAEL-829] improved names of the tests. * [BAEL-872] map and flatMap difference. * removed duplicated countingChars class. * [BAEL-872] changed Object into List. * [BAEL-872] improved code for map() and flatMap() article.
1 parent d3597a8 commit b7b1693

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.baeldung.java8;
2+
3+
import org.junit.Test;
4+
5+
import java.util.Arrays;
6+
import java.util.Collection;
7+
import java.util.List;
8+
import java.util.Optional;
9+
import java.util.stream.Collectors;
10+
import java.util.stream.Stream;
11+
12+
import static java.util.Arrays.asList;
13+
import static org.junit.Assert.assertEquals;
14+
15+
public class Java8MapAndFlatMap {
16+
17+
@Test
18+
public void givenStream_whenCalledMap_thenProduceList() {
19+
List<String> myList = Stream.of("a", "b")
20+
.map(String::toUpperCase)
21+
.collect(Collectors.toList());
22+
assertEquals(asList("A", "B"), myList);
23+
}
24+
25+
@Test
26+
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
27+
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
28+
System.out.println(list);
29+
30+
System.out.println(list
31+
.stream().flatMap(Collection::stream)
32+
.collect(Collectors.toList()));
33+
}
34+
35+
@Test
36+
public void givenOptional_whenCalledMap_thenProduceOptional() {
37+
Optional<String> s = Optional.of("test");
38+
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
39+
}
40+
41+
@Test
42+
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
43+
assertEquals(Optional.of(Optional.of("STRING")), Optional
44+
.of("string")
45+
.map(s -> Optional.of("STRING")));
46+
47+
assertEquals(Optional.of("STRING"), Optional
48+
.of("string")
49+
.flatMap(s -> Optional.of("STRING")));
50+
}
51+
52+
}

0 commit comments

Comments
 (0)