这个问题在这里已有答案:
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;
}
在上面的代码中,是否可以在guestList
方法中传递buildRate
的索引。我需要在构建Rate
时传递索引,但无法通过Stream
获得索引。
你没有提供buildRate
的签名,但我假设你想要首先传递guestList
元素的索引(在ageRate
之前)。您可以使用IntStream
获取索引而不必直接处理元素:
List<Rate> rateList = IntStream.range(0, guestList.size())
.mapToObj(i -> buildRate(i, ageRate, guestRate, guestList.get(i)))
.collect(Collectors.toList());
如果您的类路径中有Guava,那么Streams.mapWithIndex
方法(从版本21.0开始提供)正是您所需要的:
List<Rate> rateList = Streams.mapWithIndex(
guestList.stream(),
(guest, index) -> buildRate(index, ageRate, guestRate, guest))
.collect(Collectors.toList());