java8foreach
Java forEach method was introduced in Iterable interface in Java 8. Java 8 forEach method is another way that we can use to traverse through a collection.
Java forEach方法是在Java 8的 Iterable接口中引入的。 Java 8 forEach方法是我们可以用来遍历集合的另一种方法。
Java forEach (Java forEach)
Below code snippet shows the default implementation of java forEach method in Iterable interface. Read java 8 interface changes to learn more about default interface methods.
下面的代码片段显示了Iterable接口中java forEach方法的默认实现。 阅读Java 8接口更改以了解有关默认接口方法的更多信息。
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
Java forEach method performs the given action for each element of the Iterable until all elements have been processed or exception is thrown.
Java forEach方法对Iterable的每个元素执行给定的操作,直到处理完所有元素或引发异常为止。
Java 8 forEach列表示例 (Java 8 forEach List Example)
Before java 8, We could iterate over a list by using for loop or iterator.
在Java 8之前,我们可以使用for循环或iterator遍历列表。
List<String> list = getList();
//prior to java 8
//using enhanced for loop
for(String s : list){
System.out.println(s);
}
//using iterator
Iterator<String> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
Now same thing can be performed using java forEach method as shown below.
现在可以使用java forEach方法执行相同的操作,如下所示。
// Create Consumer instance
Consumer<String> action = new Consumer<String>(){
@Override
public void accept(String t) {
System.out.println(t);
}
};
//java 8 forEach
list.forEach(action);
Since Consumer is a functional interface, we can use lambda expression and write above code in one line as;
由于Consumer是一个功能性的接口 ,因此我们可以使用lambda表达式并将上述代码写成一行;
list.forEach(k -> {System.out.println(k);});
Java 8 forEach Map示例 (Java 8 forEach Map Example)
Prior to java 8, we iterate over Map elements like below.
在Java 8之前,我们对Map元素进行如下迭代。
Map<Integer,String> map = getMap();
//iteration prior to java 8
Set<Integer> keySet = map.keySet();
//using enhanced for loop
for (Integer i : keySet){
System.out.println(map.get(i));
}
//using iterator
Iterator<Integer> it = keySet.iterator();
while(it.hasNext()){
System.out.println(map.get(it.next()));
}
Since Map doesn’t extend Iterable, forEach method is added into Map interface in java 8 and below shows the default implementation.
由于Map不扩展Iterable,因此java 8中的Map接口中添加了forEach方法,下面显示了默认实现。
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);
}
}
Let’s look at a simple example how we can use java 8 forEach with Map.
让我们看一个简单的示例,如何将Java 8 forEach与Map结合使用。
BiConsumer<Integer,String> action = new BiConsumer<Integer, String>(){
@Override
public void accept(Integer t, String u) {
System.out.println(u);
}
};
//java 8 forEach with Map
map.forEach(action);
Same code can be written using lambda expressions as below.
可以使用以下lambda表达式编写相同的代码。
map.forEach((k,v) -> {System.out.println(v);});
Java forEach的好处 (Java forEach Benefits)
I don’t see too much benefit of forEach loop except when you are using it with parallel stream. A new method was added in Collection interface to get the parallel stream.
我没有看到forEach循环有太多好处,除非将它与并行流一起使用。 在Collection接口中添加了一种新方法来获取并行流。
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
So if we have to iterate over a collection and we are not bothered about sequential iteration, then we can use parallel stream with forEach loop as shown below.
因此,如果我们必须遍历一个集合,而不必担心顺序迭代,那么可以将并行流与forEach循环一起使用,如下所示。
//parallel operation using stream
list.parallelStream().forEach(action);
That’s all for Java forEach method. I hope you will find some use case for java 8 forEach method in parallel processing.
这就是Java forEach方法的全部内容。 希望您能在并行处理中找到Java 8 forEach方法的一些用例。
翻译自: https://www.journaldev.com/13941/java-foreach-java-8-foreach
java8foreach