Get Index while iterating list with stream
Solution 1
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());
Solution 2
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());
Related videos on Youtube
Amit
Software Engineer By profession. Deep love with sports, Football ( Hate to say Soccer) , Cricket, Tennis and many others Developing systems using php, java, c# I like to help people when they are stuck with something
Updated on August 21, 2022Comments
-
Amit almost 2 years
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
insidebuildRate
method. I need to pass index also while buildingRate
but could not manage to get index withStream
.-
Jason Hu over 6 yearsyou will need to fold(or reduce in java8). it's very annoying that java 8 implements (so-called) functional programming without providing tuple.
-
-
Amit over 6 yearsIs there
Instream. range(0, size). stream()
? -
Jacob G. over 6 years
IntStream
is already aStream
, so there's no need to re-stream it. -
Amit over 6 yearsThere is one extra
.stream
in your code, please remove that. I will accept your answer -
Jacob G. over 6 yearsOh whoops! I originally copied your code and forgot to remove the call to
stream
. My apologies. -
Holger over 6 yearsTo be nitpicking,
IntStream
is not already aStream
, but supports almost the same operations, as far as there areint
specific specializations. For all other operations, you can callboxed()
to truly have aStream
.