Get Index while iterating list with stream [duplicate]

柔情痞子 提交于 2020-07-18 04:28:19

问题


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.


回答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());



回答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());


来源:https://stackoverflow.com/questions/49080255/get-index-while-iterating-list-with-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!