Java 8 | How to do forEach reverse

97 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.

PERIOD

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));

Output

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.

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.