How can I extract two elements from a Stream by their positions? For example I'm trying to extract element 0 and 1 (these numbers are arbitrary!) from a Stream<String>
. A naive approach is this:
List<String> strings = Arrays.asList("s0", "s1", "s2", "s3", "s4");
Consumer<String> c0 = s -> System.out.println("c0.accept(" + s + ")");
Consumer<String> c1 = s -> System.out.println("c1.accept(" + s + ")");
strings.stream().skip(0).peek(c0).skip(1).peek(c1).findAny();
This produces the following output:
c0.accept(s0)
c0.accept(s1)
c1.accept(s1)
I understand that it's because s0
will enter the stream, encounter skip(0)
, then peek(c0)
(which gives the the first line) and then skip(1)
, which will skip this element and then apparently continue with the next element from the beginning of the stream.
I thought I could use these consumers to extract the strings, but c0
would be overwritten by the second element:
String[] extracted = new String[2];
c0 = s -> extracted[0];
c1 = s -> extracted[1];
EDIT:
These are the characteristics of the stream:
- There's a stream only, not a list or an array
- The stream is possibly infinite
- The stream can be made sequential