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 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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With