Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Index while iterating list with stream [duplicate]

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.

like image 359
Amit Avatar asked Mar 03 '18 03:03

Amit


People also ask

Can we get index in stream?

You can use the range method of IntStream to apply forEach with index. As we can access the elements in an array or a collection are accessible using an index, you can get an IntStream of array indices, ranging from 0 to n-1 , where n is the size of the collection.

How do I find stream index?

Create an AtomicInteger for index. Get the Stream from the array using Arrays. stream() method. Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.

How do I get unique values from a stream?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.


2 Answers

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());
like image 180
Jacob G. Avatar answered Sep 17 '22 13:09

Jacob G.


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());
like image 21
fps Avatar answered Sep 20 '22 13:09

fps