forked from igor-baiborodine/java-various-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeAndFlatMapExample.java
More file actions
46 lines (38 loc) · 1.24 KB
/
Copy pathMergeAndFlatMapExample.java
File metadata and controls
46 lines (38 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.kiroule.ocpupgradejava8.topic6_3;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Igor Baiborodine
*/
public class MergeAndFlatMapExample {
public static void main(String... args) {
List<String> phrases = Arrays.asList(
"sporadic perjury",
"confounded skimming",
"incumbent jailer",
"confounded jailer");
List<String> uniqueWords = phrases
.stream()
.flatMap(phrase -> Stream.of(phrase.split(" +")))
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);
Map<Integer, String> lengthToWordsMap = new HashMap<>();
Consumer<String> action = w -> {
BiFunction<String, String, String>
remappingFunction =
(value, newValue) -> value + ", " + newValue;
lengthToWordsMap.merge(w.length(), w, remappingFunction);
};
uniqueWords.forEach(action);
lengthToWordsMap
.forEach((key, value) -> System.out.printf("%nWords with length %d: %s", key, value));
}
}