[BAEL-872] map and flatMap difference (#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 66471cf0574c85f8ff514ec4caf5ba44ebba1a74.

* Revert of evaluation task "injecting beans"

This reverts commit d2ac20185e636245bc0ae0b4ccb952965de88e28.

* [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.
This commit is contained in:
Tomasz Sobala 2017-06-02 08:06:12 +02:00 committed by Grzegorz Piwowarek
parent d3597a84c7
commit b7b1693df5
1 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,52 @@
package com.baeldung.java8;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class Java8MapAndFlatMap {
@Test
public void givenStream_whenCalledMap_thenProduceList() {
List<String> myList = Stream.of("a", "b")
.map(String::toUpperCase)
.collect(Collectors.toList());
assertEquals(asList("A", "B"), myList);
}
@Test
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list);
System.out.println(list
.stream().flatMap(Collection::stream)
.collect(Collectors.toList()));
}
@Test
public void givenOptional_whenCalledMap_thenProduceOptional() {
Optional<String> s = Optional.of("test");
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
}
@Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional
.of("string")
.map(s -> Optional.of("STRING")));
assertEquals(Optional.of("STRING"), Optional
.of("string")
.flatMap(s -> Optional.of("STRING")));
}
}