The Java forEach is a utility method. It helps iterate over a collection such as (list, set, or map) & stream and perform a certain action on each element of it.
- A new method forEach() is introduced in Java 8 to iterate over elements.
- It is a default method available in the Iterable interface.
- We can use forEach to iterate over a collection and perform a certain action on each element.
- A class that implements the Consumer interface contains the action and it passes the action as an argument to forEach.
- The Consumer interface is a functional interface with a single abstract method.
- This method accepts a single parameter which is a functional interface. So, one can pass a lambda expression as an argument.
- The method accepts an input and returns no result.
- Maps are not Iterable, however, maps do provide their own variant of forEach that accepts a BiConsumer.
- Iterable’s forEach introduces A BiConsumer instead of a Consumer. As a result, an action can be performed on both the key and value of a Map simultaneously.
- The forEach loop just needs to know what is to be done and all the work of iterating will be taken care of internally. However, in a traditional loop, we need to tell how to perform the iterations.
List<String> names = Arrays.asList("A", "B", "C", "D"); names.forEach(System.out::println); names.forEach(name -> System.out.println(name)); ArrayList<String> namesList = new ArrayList<>(names); Consumer<String> lambdaExp = x -> System.out.println(x.toLowerCase()); namesList.forEach(name -> System.out.println(name.toLowerCase())); namesList.forEach(lambdaExp);
HashMap<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); Consumer<Map.Entry<String, Integer>> action = System.out::println; map.entrySet().forEach(action); Consumer<String> actionOnKeys = System.out::println; map.keySet().forEach(actionOnKeys); Consumer<Integer> actionOnValues = System.out::println; map.values().forEach(actionOnValues); map.forEach((key, value) -> System.out.println(key + " " + value));
List<Integer> numberList = Arrays.asList(1,2,3,4,5); Consumer<Integer> action = System.out::println; numberList.stream() .filter(n -> n%2 == 0) .filter(action);