Get Index while iterating list with stream

13,448

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());
Share:
13,448

Related videos on Youtube

Amit
Author by

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, 2022

Comments

  • Amit
    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 inside buildRate method. I need to pass index also while building Rate but could not manage to get index with Stream.

    • Jason Hu
      Jason Hu over 6 years
      you will need to fold(or reduce in java8). it's very annoying that java 8 implements (so-called) functional programming without providing tuple.
  • Amit
    Amit over 6 years
    Is there Instream. range(0, size). stream() ?
  • Jacob G.
    Jacob G. over 6 years
    IntStream is already a Stream, so there's no need to re-stream it.
  • Amit
    Amit over 6 years
    There is one extra .stream in your code, please remove that. I will accept your answer
  • Jacob G.
    Jacob G. over 6 years
    Oh whoops! I originally copied your code and forgot to remove the call to stream. My apologies.
  • Holger
    Holger over 6 years
    To be nitpicking, IntStream is not already a Stream, but supports almost the same operations, as far as there are int specific specializations. For all other operations, you can call boxed() to truly have a Stream.