forked from AndrewProgramming/JavaTutorialCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectGroupDemo.java
More file actions
36 lines (31 loc) · 1.46 KB
/
CollectGroupDemo.java
File metadata and controls
36 lines (31 loc) · 1.46 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
package stream;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class CollectGroupDemo {
public static void main(String[] args) {
String[] names = {"John", "Peter", "Susan", "Kim", "Jen",
"George", "Alan", "Stacy", "Steve", "john"};
Map<String, Long> map1 = Stream.of(names).map(e -> e.toUpperCase()).collect(
Collectors.groupingBy(e -> e, Collectors.counting()));
System.out.println(map1);
Map<Character, Long> map2 = Stream.of(names)
.collect(Collectors.groupingBy(e -> e.charAt(0), TreeMap::new,
Collectors.counting()));
System.out.println(map2);
int[] values = {2, 3, 4, 1, 2, 3, 2, 3, 4, 5, 1, 421};
IntStream.of(values).mapToObj(e -> e)
.collect(Collectors.groupingBy(e -> e, TreeMap::new, Collectors.counting())).
forEach((k, v) -> System.out.println(k + " occurs " + v + (v > 1 ? " times " : " time ")));
MyStudent[] students = {new MyStudent("John", "Lu", "CS", 32, 78),
new MyStudent("Susan", "Yao", "Math", 31, 85.4),
new MyStudent("Kim", "Johnson", "CS", 30, 78.1)};
System.out.printf("%10s%10s\n", "Department", "Average");
Stream.of(students).collect(Collectors.
groupingBy(MyStudent::getMajor, TreeMap::new,
Collectors.averagingDouble(MyStudent::getScore))).
forEach((k, v) -> System.out.printf("%10s%10.2f\n", k, v));
}
}