Java forEach() 方法是一个实用函数,用于迭代集合,例如(List、Collect或Map)和 Stream。它用于对集合中的每个元素执行给定的操作。
forEach()
方法已添加到以下位置:
Iterable
接口 – 这使得 Iterable.forEach()
方法可用于除 Map
之外的所有集合类Map
接口 – 这使得 forEach()
操作可用于所有Map类。Stream
接口 – 这使得 forEach()
和 forEachOrdered()
操作可用于所有类型的流.给定的代码片段显示了 Iterable 接口中的 .Consumer-">forEach()
方法。
它在内部使用 增强的 for 循环。因此,使用新的 for 循环将提供与 forEach()
方法相同的效果和性能。
default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }
forEach()
方法为 Iterable
的每个元素执行给定的 action
,直到所有元素都已处理或 action 抛出异常。
List<String> names = Arrays.asList("Alex", "Brian", "Charles"); names.forEach(System.out::println);
程序输出:
Alex Brian Charles
在上面的示例中,action
表示接受单个输入参数并且不返回任何结果的操作。它是 Consumer
接口的一个实例。
通过像这样创建消费者操作,我们可以指定多个语句,以类似于方法的语法执行。
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);
程序输出:
ALEX BRIAN CHARLES
此方法为每个 执行给定的 BiConsumer 操作此
,直到处理完所有条目或操作引发异常。Map
中的条目
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<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));
程序输出:
Key = A, Value = Alex Key = B, Value = Brian Key = C, Value = Charles
我们还可以创建一个自定义 BiConsumer 操作,它将从 Map
中获取键值对,并一次处理一个条目。
BiConsumer<String, Integer> action = (a, b) -> { //Process the entry here as per business 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
在Stream
中,forEach()
和forEachOrdered()
是终端操作。
与 Iterable
类似,流 forEach()
方法对流的每个元素执行一个操作。
对于顺序流,元素的顺序(在迭代期间)与流源中的顺序相同,因此无论我们使用 forEach()
还是 <代码>forEachOrdered()。
在使用并行流 时,如果元素的顺序在迭代期间很重要,请使用forEachOrdered()
。 forEach()
方法不保证元素排序以提供并行性的优势。
在此示例中,我们打印数字流中的所有偶数。
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
在此示例中,我们打印数字流中的所有偶数。
List<Integer> numberList = Arrays.asList(1,2,3,4,5); Consumer<Integer> action = System.out::println; numberList.stream() .filter(n -> n%2 == 0) .parallel() .forEachOrdered( action );
程序输出。
2 4
学习快乐!!
地址:https://www.cundage.com/article/foreach-method-example.html