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\",
You can use IntStream.iterate() to get the index:
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
List nameList = IntStream.iterate(0, i -> i < names.length, i -> i + 1)
.filter(i -> names[i].length() <= i)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
This only works for Java 9 upwards in Java 8 you can use this:
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
List nameList = IntStream.iterate(0, i -> i + 1)
.limit(names.length)
.filter(i -> names[i].length() <= i)
.mapToObj(i -> names[i])
.collect(Collectors.toList());