Get index when navigating list with stream

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, you can pass the index guestListinside the method buildRate. I need to also pass the index when building Rate, but could not get the index from Stream.

+4
source share
2 answers

You did not specify a signature buildRate, but I assume that you want to pass the index of the elements guestList(before ageRate) first. You can use IntStreamto get indexes, and not to directly manipulate elements:

List<Rate> rateList = IntStream.range(0, guestList.size())
                               .mapToObj(i -> buildRate(i, ageRate, guestRate, guestList.get(i)))
                               .collect(Collectors.toList());
+4
source

If you have Guava in your classpath, the method Streams.mapWithIndex(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());
+2
source

Source: https://habr.com/ru/post/1694383/


All Articles