Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream array in reverse order / Java

Reversing an ordered stream

Does streaming an array and then reversing the order of the stream result in the overhead (e.g. like the necessity to fully stream the array first and then iterate on it backwards)?

Using a helper structure

final Object[] arr; // assume this is filled
List<Integer> list = Arrays.asList(arr);
Collections.reverse(list);
list.stream();

Is the only way to circumvent overhead (e.g. like the creation of an additional List) to iterate over the array in reverse order?

like image 887
Semnodime Avatar asked Jun 30 '26 22:06

Semnodime


2 Answers

Does streaming an array and then reversing the order of the stream result in the overhead

Yes.

Is the only way to circumvent overhead (e.g. like the creation of an additional List) to iterate over the array in reverse order?

Yes, do it with an IntStream:

IntStream.range(0, arr.length).mapToObj(i -> arr[arr.length-1-i])
like image 132
Andy Turner Avatar answered Jul 02 '26 10:07

Andy Turner


Java 21 adds the reversed method to List, which is a view of the original list in reversed order. This can be used in conjunction with Arrays.asList, which creates a List view of the array:

final Object[] arr; // assume this is filled
Stream<Object> stream = Arrays.asList(arr).reversed().stream();

Both Arrays.asList and reversed are minimalistic wrapper views of the underlying array, and do not copy the array or otherwise have much overhead.

like image 31
M. Justin Avatar answered Jul 02 '26 12:07

M. Justin