使用流[重复]迭代列表时获取索引

问题描述 投票:4回答:2

这个问题在这里已有答案:

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获得索引。

java java-8 java-stream
2个回答
4
投票

你没有提供buildRate的签名,但我假设你想要首先传递guestList元素的索引(在ageRate之前)。您可以使用IntStream获取索引而不必直接处理元素:

List<Rate> rateList = IntStream.range(0, guestList.size())
                               .mapToObj(i -> buildRate(i, ageRate, guestRate, guestList.get(i)))
                               .collect(Collectors.toList());

3
投票

如果您的类路径中有Guava,那么Streams.mapWithIndex方法(从版本21.0开始提供)正是您所需要的:

List<Rate> rateList = Streams.mapWithIndex(
        guestList.stream(),
        (guest, index) -> buildRate(index, ageRate, guestRate, guest))
    .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.