forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
69 lines (54 loc) · 2.51 KB
/
Copy pathMain.java
File metadata and controls
69 lines (54 loc) · 2.51 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package modern.challenge;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
List<Melon> melons = Arrays.asList(new Melon("Gac", 2000),
new Melon("Hemi", 1600), new Melon("Gac", 3000),
new Melon("Apollo", 2000), new Melon("Horned", 1700));
System.out.println("map() examples:");
List<String> melonNames = melons.stream()
.map(Melon::getType)
.collect(Collectors.toList());
System.out.println("\nStream<Melon> to Stream<String> "
+ "and collected in List<Stream>:\n" + melonNames);
List<Integer> melonWeights = melons.stream()
.map(Melon::getWeight)
.collect(Collectors.toList());
System.out.println("\nStream<Melon> to Stream<Integer> "
+ "and collected in List<Integer>:\n" + melonWeights);
List<Melon> lighterMelons = melons.stream()
.peek(m -> m.setWeight(m.getWeight() - 500)) // no map
.collect(Collectors.toList());
System.out.println("\nThink twice when use it to mutate state! "
+ "Setting new weights via peek():\n" + lighterMelons);
System.out.println("\n\nflatMap() examples:");
Melon[][] melonsArray = {
{new Melon("Gac", 2000), new Melon("Hemi", 1600)},
{new Melon("Gac", 2000), new Melon("Apollo", 2000)},
{new Melon("Horned", 1700), new Melon("Hemi", 1600)}
};
Stream<Melon[]> streamOfMelonsArray = Arrays.stream(melonsArray);
List<Melon> distinctMelons = streamOfMelonsArray
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
System.out.println("Distinct melons: " + distinctMelons);
List<List<String>> melonLists = Arrays.asList(
Arrays.asList("Gac", "Cantaloupe"),
Arrays.asList("Hemi", "Gac", "Apollo"),
Arrays.asList("Gac", "Hemi", "Cantaloupe"),
Arrays.asList("Apollo"),
Arrays.asList("Horned", "Hemi"),
Arrays.asList("Hemi")
);
List<String> distinctNames = melonLists.stream()
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
System.out.println("Distinct names: " + distinctNames);
}
}