473 total views, 1 views today
Checkout how to do forEach reverse in Java 8.
There might be a situation where you would like traverse through your collection in reverse order. This can be achieved using traditional for-loop but can it be achieved using Java 8 forEach?
The answer is It is not possible to iterate in reverse order using forEach java 8.
The best thing you can do is to reverse your collection using java libraries and then iterate over it.
List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Orange"); list.add("Banana"); list.add("Grapes"); list.forEach((item) -> System.out.println("Before reverse "+item)); Collections.reverse(list); list.forEach((item) -> System.out.println("After reverse "+item));
Before reverse Apple Before reverse Orange Before reverse Banana Before reverse Grapes After reverse Grapes After reverse Banana After reverse Orange After reverse Apple
Please refer to How to use forEach if you would like to learn about forEach
Java 8 forEach official documentation.