Traverse foreach

Java 8’s foreach() method, which is an efficient way to traverse a collection of bookshelves, can be used to traverse a List,Stream, and has been added to the following interface

  • The Iterable interface –
  • The Map interface
  • The Stream interface

1. Iterable foreach

1.1 the foreach method

The default implementation of the foreach method in the Iterable interface is given in the following code

default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); }}

The foreach method action executes the given Iterable foreach element until all elements are handled or the action raises an exception

Example 1, a Java program that uses foreach to iterate over a list

List<String> names = Arrays.asList("Alex", "Brian", "Charles");
     
names.forEach(System.out::println);

Output:

Alex
Brian
Charles
1.2 Create Consumer Behavior — Consumer

In the example above, Action, which takes a single input parameter and returns no data, is an instance of the Consumer interface, creating a Consumer action by doing so. We plan to execute multiple statements in a similar way

public static void main(String[] args) { List<String> names = Arrays.asList("Alex", "Brian", "Charles"); }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} System.out.println(o.toUpperCase()); }}; names.forEach(makeUpperCase); } // result Alex Brian Charles

Instead of using anonymous function inner classes, you can now use Lanmbda expressions

Consumer<String> makeUpperCase = o -> System.out.println(o.toUpperCase());

2 the foreach Map

2.1 the foreach method

This method executes the given Biconsumer action to execute the entry in the map until all the data is processed or an exception is thrown

The default method in 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); }}

In example 2, the map is traversed by the foreach method

Map<String, String> map = new HashMap<String, String>(); map.put("A", "Alex"); map.put("B", "Brian"); map.put("C", "Charles"); BiConsumer<String, String> biConsumer = new BiConsumer<String,String>() { @Override public void accept(String key, String value) { System.out.println(key+" "+value); }}; map.forEach(biConsumer); } // use lambda to replace the anonymous function BiConsumer<String, String> BiConsumer = (key, value) -> system.out. println(key+" "+value);

Print the result

A Alex
B Brian
C Charles

3. Stream foreach and forEachOrdered

In the Stream foreach and foreeachOrdered are terminal operations. The Stream’s foreach methods perform an action method on each element in the map. For an order Stream, the order of the elements in the order Stream remains consistent with the order in the source Stream. When using parallel streams, the foreachOrdered method is useful. Try to use this method. Foreach cannot guarantee the order of the elements in the parallel stream

Example 3 iterates over foreach in Stream

A 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 ); Output: 2 4

Example 4 uses ForeachOrdered to traverse the stream

A 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 );