forked from nrkapri/JavaAdvancedTopics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaptoListExample.java
More file actions
62 lines (42 loc) · 1.93 KB
/
Copy pathMaptoListExample.java
File metadata and controls
62 lines (42 loc) · 1.93 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
package java8;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MaptoListExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(10, "apple");
map.put(20, "orange");
map.put(30, "banana");
map.put(40, "watermelon");
map.put(50, "dragonfruit");
System.out.println("\n1. Export Map Key to List...");
List<Integer> result = map.keySet().stream()
.collect(Collectors.toList());
result.forEach(System.out::println);
System.out.println("\n2. Export Map Value to List...");
List<String> result2 = map.values().stream()
.collect(Collectors.toList());
result2.forEach(System.out::println);
System.out.println("\n3. Export Map Value to List..., say no to banana");
List<String> result3 = map.values().stream()
.filter(x -> !"banana".equalsIgnoreCase(x))
.collect(Collectors.toList());
result3.forEach(System.out::println);
// split a map into 2 List
List<Integer> resultSortedKey = new ArrayList<>();
List<String> resultValues = map.entrySet().stream()
//sort a Map by key and stored in resultSortedKey
.sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
.peek(e -> resultSortedKey.add(e.getKey()))
.map(x -> x.getValue())
// filter banana and return it to resultValues
.filter(x -> !"banana".equalsIgnoreCase(x))
.collect(Collectors.toList());
System.out.println("Split list:");
resultSortedKey.forEach(System.out::println);
resultValues.forEach(System.out::println);
}
}