0

As long as the documentation defines the so called encounter order I think it's reasonble to ask if we can reverse that encounter order somehow. Looking at the API streams provide us with, I didn't find anything related to ordering except sorted().

If I have a stream produced say from a List can I swap two elements of that stream and therefore producing another stream with the modified encounter order.

Does it even make sense to talking about "swapping" elements in a stream or the specification say nothing about it.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
user3663882
  • 6,957
  • 10
  • 51
  • 92

1 Answers1

2

Java Stream API have no dedicated operations to reverse the encounter order or swap elements in pairs or something like this. Please note that the Stream source can be once-off (like network socket or stream of generated random numbers), so in general case you cannot make it backwards without storing everything in the memory. That's actually how sorting operation works: it dumps the whole stream content into the intermediate array, sorts it, then performs a downstream computation. So were reverse operation implemented it would work in the same way.

For particular sources like random-access list you may create reversed stream using, for example, this construct

List<T> list = ...;
Stream<T> stream = IntStream.rangeClosed(1, list.size())
                            .mapToObj(i -> list.get(list.size()-i));
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334