6 Ways To Use forEach in Java
To use for each in Java, you need to use the syntax like
1 2 3 |
iterableObject.forEach(element -> System.out.println(element)); |
Let’s have a look at some more examples of forEach in Java.
1. forEach and list
Using forEach, you can conveniently iterate over elements in a list. Have a look at the example below
1 2 3 4 5 6 7 8 |
List<Integer> integerList = new LinkedList<>(); integerList.add(1); integerList.add(2); integerList.forEach(number -> System.out.println(number)); integerList.forEach(System.out::println); |
The last two lines show two ways to achieve the same result – printing elements of the list. The first one is a standard lambda expression. The second one is the so-called method reference.
Running this code will result in
1 2 3 4 5 6 |
1 2 1 2 |
2. forEach and array
Using forEach, you can also iterate over elements in an array.
1 2 3 4 5 |
int[] numbers = new int[] {1,2,3}; Arrays.stream(numbers).forEach(number -> System.out.println(number)); Arrays.stream(numbers).forEach(System.out::println); |
As you can see, we used the syntax Arrays.stream(array).forEach(…). And we also used both lambda expression and method reference to print elements.
The result of running the code is:
1 2 3 4 5 6 7 8 |
1 2 3 1 2 3 |
3. forEach and map
This paragraph explains the usage of forEach and map.
1 2 3 4 5 6 7 |
Map<Long, String> idToName = new HashMap<>(); idToName.put(1L, "Thomas"); idToName.put(2L, "Greg"); idToName.forEach( (id, name) -> System.out.println(id + " -> " + name)); |
As you can see in the last line of code, we used the lambda expression with two parameters id and name.
Result of executing the code is:
1 2 3 4 |
1 -> Thomas 2 -> Greg |
4. Using forEach with consumer
When using forEach, you can pass as a parameter to it a consumer. Let’s have a look at the example below.
1 2 3 4 5 |
Consumer<String> stringConsumer = string -> System.out.println(string); String[] names = {"Adam", "Eddie", "Thomas"}; Arrays.stream(names).forEach(stringConsumer); |
Executing the code will print to the console:
1 2 3 4 5 |
Adam Eddie Thomas |
5. Using forEach with streams
You can also use forEach when working with streams.
1 2 3 4 5 6 |
List<Integer> integers = Arrays.asList(1,2,3,4,5,6); integers.stream() .filter(number -> number > 3) .forEach(System.out::println); |
In the example above, we firstly created a list of integers from 1 to 6. After that, we filtered numbers greater than 3. And lastly, we printed them to the console.
Running this code will print:
1 2 3 4 5 |
4 5 6 |
6. forEach and Collection interface
You can also use forEach with the Collection interface.
1 2 3 4 5 6 7 |
List<Integer> integerList = Arrays.asList(1,2,3,4,5,6); Collection<Integer> integerCollection = new HashSet<>(integerList); integerCollection.stream() .forEach(System.out::println); |
Executing the code will print
1 2 3 4 5 6 7 8 |
1 2 3 4 5 6 |