Get Index while iterating list with stream
You haven't provided the signature of buildRate
, but I'm assuming you want the index of the elements of guestList
to be passed in first (before ageRate
). You can use an IntStream
to get indices rather than having to deal with the elements directly:
List<Rate> rateList = IntStream.range(0, guestList.size())
.mapToObj(index -> buildRate(index, ageRate, guestRate, guestList.get(index)))
.collect(Collectors.toList());
If you have Guava in your classpath, the Streams.mapWithIndex
method (available since version 21.0) is exactly what you need:
List<Rate> rateList = Streams.mapWithIndex(
guestList.stream(),
(guest, index) -> buildRate(index, ageRate, guestRate, guest))
.collect(Collectors.toList());