-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForEachSample.java
More file actions
104 lines (87 loc) · 2.66 KB
/
ForEachSample.java
File metadata and controls
104 lines (87 loc) · 2.66 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package example.ForEachExample;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Foreach example.
*
* Reference:
* - https://beginnersbook.com/2017/10/java-8-foreach/
* - https://www.runoob.com/java/java-hashmap.html
*/
public class ForEachSample {
public static void main(String[] args) {
// foreach to iterate a Map.
// MapAndHasMapExample();
// foreach to iterate a List.
// ListExample();
// foreach method to iterate a stream.
StreamExample();
// foreach order method to iterate a stream.
StreamForEachOrder();
}
public static void MapAndHasMapExample() {
Map<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(1, "apple");
hmap.put(2, "orange");
hmap.put(3, "tiger");
hmap.put(4, "dog");
hmap.put(5, "cat");
hmap.put(6, "cat");
hmap.forEach((key, value) -> {
System.out.println("key = " + key + " " + "value = " + value);
if (value.equals("cat")) {
System.out.println("got the cat.");
}
if (key % 2 == 0) {
System.out.println("key: " + key + "; value: " + value);
}
});
}
public static void ListExample() {
List<String> fruits = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");
fruits.add("Pear");
fruits.add("Mango");
fruits.forEach(s -> {
System.out.println(s);
});
}
public static void StreamExample() {
List<String> list = new ArrayList<String>();
list.add("Michonne");
list.add("Maggie");
list.add("Rick");
list.add("Merle");
list.add("Governor");
list.stream()
.filter(f -> f.startsWith("M"))
.forEach(s -> {
System.out.println(s);
});
// 另一種寫法
//! System.out::println
// list.stream()
// .filter(f -> f.startsWith("M"))
// .forEach(System.out::println);
}
public static void StreamForEachOrder() {
//! 需確認是否有按照順序?
//! parallel()?
List<String> list = new ArrayList<String>();
list.add("Michonne");
list.add("Maggie");
list.add("Rick");
list.add("Merle");
list.add("Governor");
list.stream()
.filter(f -> f.startsWith("M"))
.parallel()
.forEachOrdered(n -> {
System.out.println(n);
});
}
}