In this article we present Java 8 forEach on examples. These are very convenient methods for use with Lambda Expressions and method references.
Classical List for-each loop
Since Java 5 there is for-each loop that allows to easily go through Iterables:
List<Integer> numbers = asList(1, 2, 3); for (Integer x : numbers) { System.out.println(x); }
A nice thing about the for-each loop is that JVM can optimize it.
Java 8 forEach on List
Java 8 shipped with default methods in interfaces and one of them is java.lang.Iterable.forEach(Consumer<? super T> action). It is implemented using classical for-each loop with check that action is not null. You can pass there method references like here:
List<Integer> numbers = asList(1, 2, 3); numbers.forEach(System.out::println);
Or Java 8 Lambda Expressions thusly:
List<Integer> numbers = asList(1, 2, 3); numbers.forEach(x -> { System.out.println("Number: " + x); });
Java 8 forEach on Set
The same Java 8 forEach method works with Sets:
Set<Integer> numbers = new HashSet<>(asList(1, 2, 3)); numbers.forEach(System.out::println);
Classical Map for-each loop
Before Java 8 one could process Map using for-each loop on entry set:
Map<Integer, String> languages = new HashMap<>(); languages.put(1, "Java"); languages.put(2, "Clojure"); languages.put(3, "Scala"); for (Entry<Integer,String> lang : languages.entrySet()) { System.out.printf("%d: %s%n", lang.getKey(), lang.getValue()); }
Java 8 forEach on Map
In Java 8 a new forEach(BiConsumer<? super K, ? super V> action) has been added to the Map interface. Underneath it is using for-each loop through entry set as above, but is simpler to use:
Map<Integer, String> languages = new HashMap<>(); languages.put(1, "Java"); languages.put(2, "Clojure"); languages.put(3, "Scala"); languages.forEach((id, name) -> System.out.printf("%d: %s%n", id, name));
References:
- Check out Java Util Tutorial for more Java 8 methods on Collections
- Check nullness using Objects.requireNonNull