Traverse foreach

Java 8’s foreach() method is an effective way to traverse a collection of bookshelves, including lists, streams, 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 following code gives the default implementation of the foreach method in the Iterable interface

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

The foreach method action executes a given Iterable on each element until all elements are handled or the action throws an exception

Example 1, a Java program that iterates through a list using foreach

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

Copy the code

Output:

Alex
Brian
Charles
Copy the code
1.2 Create consumer behavior — Consumer

In the above example,action, which takes a single input parameter and does not return any data, is an instance of the Consumer interface by creating a Consumer action. We specify that we want to execute multiple statements with similar syntax

public static void main(String[] args) {

		List<String> names = Arrays.asList("Alex"."Brian"."Charles");

		// Create a consume operation

		Consumer<String> makeUpperCase = new Consumer<String>() {
			@Override
			public void accept(String o) { System.out.println(o.toUpperCase()); }}; names.forEach(makeUpperCase); }/ / the result
ALEX
BRIAN
CHARLES
Copy the code

Using anonymous function inner classes can now be replaced with lanmbda expressions

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

2 the foreach Map

2.1 the foreach method

The method executes the given BiConsumer action to execute the map entry until all data is processed, or throws an exception

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 newConcurrentModificationException(ise); } action.accept(k, v); }}Copy the code

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); }// Replace anonymous functions with lambda expressions
BiConsumer<String, String> biConsumer = (key, value) -> System.out.println(key+""+value);

Copy the code

Print the result

A Alex
B Brian
C Charles
Copy the code

3. Stream foreach and forEachOrdered

Foreach and foreEachOrdered are both terminal operations in a Stream. The Stream’s foreach method performs an action on each element in the map. For ordered streams, the order of the elements remains the same as the order in the source Stream. When using parallel streams, the foreachOrdered method works well. Use this method whenever possible. Foreach cannot guarantee the order of elements in a parallel stream

Example 3: Traversing a Stream through 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 ); Output:2      4
Copy the code

Example 4: Use foreachOrdered to traverse the stream

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 );
Copy the code