This question already has answers here:
Closed 2 years ago.
List<Rate> rateList =
guestList.stream()
.map(guest -> buildRate(ageRate, guestRate, guest))
.collect(Collectors.toList());
class Rate {
protected int index;
protected AgeRate ageRate;
protected GuestRate guestRate;
protected int age;
}
In the above code, is it possible to pass index of guestList
inside buildRate
method. I need to pass index also while building Rate
but could not manage to get index 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());