在使用流迭代列表时获取索引 [英] Get Index while iterating 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;
}
在上面的代码中,可以在buildRate
方法内传递guestList
的索引.我在构建Rate
时也需要传递索引,但是无法通过Stream
获取索引.
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
.
推荐答案
您尚未提供buildRate
的签名,但是我假设您希望首先传递guestList
元素的索引. (在ageRate
之前).您可以使用IntStream
获取索引,而不必直接处理元素:
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());
这篇关于在使用流迭代列表时获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文