Java8 forEach
Java forEach 是一种实用程序方法,用于迭代集合(如列表、集或映射)和流,并针对其的每个元素执行特定操作。
1. Java 8 forEach方法
1.1 Iterable.forEach()
下边代码展示了Iterable接口中forEach方法的默认实现。这使得该方法可以用于除了Map之外的所有集合
Iterable.java
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
上述方法对可迭代的每个元素执行给定操作,直到处理所有元素或操作引发异常。
该操作表示接受单个输入参数且不返回任何结果的操作。它是Consumer接口的实例。
使用 forEach() 方法
List<String> names = Arrays.asList("Alex", "Brian", "Charles");
names.forEach(System.out::println);
//Console output
Alex
Brian
Charles
可以使用这个简单的语法创建自定义的Consumer。这里的对象类型应该替换为集合或流中的元素类型
Custom consumer action
List<String> names = Arrays.asList("Alex", "Brian", "Charles");
Consumer<String> makeUpperCase = new Consumer<String>()
{
@Override
public void accept(String t)
{
System.out.println(t.toUpperCase());
}
};
names.forEach(makeUpperCase);
//Console output
ALEX
BRIAN
CHARLES
1.2 Map.forEach()
此方法对于map中的每个元素执行指定的BiConsumer操作,直到处理所有操作或者引发异常。
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
使用Map.forEach()方法
Map<String, String> map = new HashMap<String, String>();
map.put("A", "Alex");
map.put("B", "Brian");
map.put("C", "Charles");
map.forEach((k, v) ->
System.out.println("Key = " + k + ", Value = " + v));
//Console Output
Key = A, Value = Alex
Key = B, Value = Brian
Key = C, Value = Charles
类似List例子,我们可以创建一个自定义的biconsumer action,从Map中获取键值对,并依次执行。
BiConsumer<String, Integer> action = (a, b) ->
{
System.out.println("Key is : " + a);
System.out.println("Value is : " + b);
};
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.forEach(action);
程序输出
Key is : A
Value is : 1
Key is : B
Value is : 2
Key is : C
Value is : 3
2. 使用List的Java forEach例子
Java程序在流里对所有元素进行迭代并执行对应的操作。在这个例子中,我们正在打印所有偶数
List<Integer> numberList = Arrays.asList(1,2,3,4,5);
Consumer<Integer> action = System.out::println;
numberList.stream()
.filter(n -> n%2 == 0)
.forEach( action );
程序输出:
2
4
3. 使用Map的forEach例子
在上面的程序中,我们已经对HashMap中的所有元素进行了迭代并执行对应操作。
我们也可以对map中的key和值进行迭代,并执行任何操作。
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
//1. Map entries
Consumer<Map.Entry<String, Integer>> action = System.out::println;
map.entrySet().forEach(action);
//2. Map keys
Consumer<String> actionOnKeys = System.out::println;
map.keySet().forEach(actionOnKeys);
//3. Map values
Consumer<Integer> actionOnValues = System.out::println;
map.values().forEach(actionOnValues);
程序输出:
A=1
B=2
C=3
A
B
C
1
2
3







网友评论