'Java8 Stream How to iterate through elements from back to front? [duplicate]
For example:
List<Integer> list = Lists.newArrayList(3, 1, 2)
for(int i = list.size() - 1; i>=0; i--) {
System.out.println(list.get(i));
}
How do I go about implementing the above code in Java8 Stream?
Solution 1:[1]
You can try the below piece of code -
ListIterator<Integer> iterator = list.listIterator(list.size());
Stream.generate(iterator::previous)
.limit(list.size())
.forEach(System.out::println);
Solution 2:[2]
What if something like:
List<Integer> list = Arrays.asList(3, 1, 2);
Collections.reverse(list);
list.forEach(System.out::println);
Solution 3:[3]
int[] array = {3, 1, 2};
IntStream.rangeClosed(1, array.length)
.mapToObj(i -> array[array.length - i])
.forEach(System.out::println);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dhanraj |
| Solution 2 | Andriy Zhuk |
| Solution 3 | Tyler2P |
