Is there a concise way to iterate over a stream whilst having access to the index in the stream?
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
List<String> nameList;
Stream<Integer> indices = intRange(1, names.length).boxed();
nameList = zip(indices, stream(names), SimpleEntry::new)
.filter(e -> e.getValue().length() <= e.getKey())
.map(Entry::getValue)
.collect(toList());
which seems rather disappointing compared to the LINQ example given there
string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();
Is there a more concise way?
Further it seems the zip has either moved or been removed...
If you are trying to get an index based on a predicate, try this:
If you only care about the first index:
Or if you want to find multiple indexes:
Add
.orElse(-1);
in case you want to return a value if it doesn't find it.There isn't a way to iterate over a
Stream
whilst having access to the index because aStream
is unlike anyCollection
. AStream
is merely a pipeline for carrying data from one place to another, as stated in the documentation:No storage. A stream is not a data structure that stores elements; instead, they carry values from a source (which could be a data structure, a generator, an IO channel, etc) through a pipeline of computational operations.
Of course, as you appear to be hinting at in your question, you could always convert your
Stream<V>
to aCollection<V>
, such as aList<V>
, in which you will have access to the indexes.In addition to protonpack, jOOλ's Seq provides this functionality (and by extension libraries that build on it like cyclops-react, I am the author of this library).
Seq also supports just Seq.of(names) and will build a JDK Stream under the covers.
The simple-react equivalent would similarly look like
The simple-react version is more tailored for asynchronous / concurrent processing.
Just for completeness here's the solution involving my StreamEx library:
Here we create an
EntryStream<Integer, String>
which extendsStream<Entry<Integer, String>>
and adds some specific operations likefilterKeyValue
orvalues
. AlsotoList()
shortcut is used.I've used the following solution in my project. I think it is better than using mutable objects or integer ranges.
I found the solutions here when the Stream is created of list or array (and you know the size). But what if Stream is with unknown size? In this case try this variant:
Usage: