-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupByCountSort.java
More file actions
52 lines (43 loc) · 1.34 KB
/
GroupByCountSort.java
File metadata and controls
52 lines (43 loc) · 1.34 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
package streams;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class GroupByCountSort {
public static List<String> items = new ArrayList<String>();
static {
items.add("apple");
items.add("apple");
items.add("apple");
items.add("banana");
items.add("banana");
items.add("orance");
items.add("papaya");
items.add("pinapple");
}
public static void main(String[] args) {
countEx();
System.out.println("<------------------------------------------->");
sorting();
}
private static void countEx() {
Map<String,Long> result = items.stream().collect(Collectors.groupingBy(
Function.identity(),Collectors.counting()));
result.forEach((k,v)->{
System.out.println(k + " " + v);
});
}
private static void sorting() {
Map<String, Long> result = items.stream().collect(
Collectors.groupingBy(Function.identity(),Collectors.counting())
);
Map<String, Long> finalMap = new LinkedHashMap<>();
result.entrySet().stream().sorted(
Map.Entry.<String, Long>comparingByValue().reversed()).forEachOrdered(e->finalMap.put(e.getKey(), e.getValue()));
finalMap.forEach((k,v)->{
System.out.println(k + " " + v);
});
}
}