是否有一种简洁的方法在流上迭代,同时访问流中的索引?

String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};

List<String> nameList;
Stream<Integer> indices = intRange(1, names.length).boxed();
nameList = zip(indices, stream(names), SimpleEntry::new)
        .filter(e -> e.getValue().length() <= e.getKey())
        .map(Entry::getValue)
        .collect(toList());

与这里给出的LINQ示例相比,这似乎相当令人失望

string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();

有更简洁的方式吗?

此外,似乎拉链已经移动或被拆除…


当前回答

没有一种方法可以在访问索引的同时遍历流,因为流不同于任何集合。Stream只是一个将数据从一个地方传输到另一个地方的管道,如文档中所述:

没有存储。流不是存储元素的数据结构;相反,它们通过计算操作管道携带来自源(可以是数据结构、生成器、IO通道等)的值。

当然,正如您在问题中暗示的那样,您总是可以将Stream<V>转换为Collection<V>,例如List<V>,在其中您将可以访问索引。

其他回答

没有一种方法可以在访问索引的同时遍历流,因为流不同于任何集合。Stream只是一个将数据从一个地方传输到另一个地方的管道,如文档中所述:

没有存储。流不是存储元素的数据结构;相反,它们通过计算操作管道携带来自源(可以是数据结构、生成器、IO通道等)的值。

当然,正如您在问题中暗示的那样,您总是可以将Stream<V>转换为Collection<V>,例如List<V>,在其中您将可以访问索引。

最简洁的方法是从一系列指数开始:

String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
IntStream.range(0, names.length)
         .filter(i -> names[i].length() <= i)
         .mapToObj(i -> names[i])
         .collect(Collectors.toList());

结果列表只包含“Erik”。


当你习惯for循环时,另一种看起来更熟悉的方法是使用可变对象维护一个临时计数器,例如AtomicInteger:

String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
AtomicInteger index = new AtomicInteger();
List<String> list = Arrays.stream(names)
                          .filter(n -> n.length() <= index.incrementAndGet())
                          .collect(Collectors.toList());

注意,在并行流上使用后一种方法可能会中断,因为项目不一定会“按顺序”处理。

你可以创建一个静态的内部类来封装索引器,就像我在下面的例子中需要做的那样:

static class Indexer {
    int i = 0;
}

public static String getRegex() {
    EnumSet<MeasureUnit> range = EnumSet.allOf(MeasureUnit.class);
    StringBuilder sb = new StringBuilder();
    Indexer indexer = new Indexer();
    range.stream().forEach(
            measureUnit -> {
                sb.append(measureUnit.acronym);
                if (indexer.i < range.size() - 1)
                    sb.append("|");

                indexer.i++;
            }
    );
    return sb.toString();
}

这个问题(流方式获取第一个元素匹配布尔值的索引)已将当前问题标记为重复,所以我无法回答它;我在这里回答。

下面是获得匹配索引的通用解决方案,不需要外部库。

如果你有一个清单。

public static <T> int indexOf(List<T> items, Predicate<T> matches) {
        return IntStream.range(0, items.size())
                .filter(index -> matches.test(items.get(index)))
                .findFirst().orElse(-1);
}

像这样叫它:

int index = indexOf(myList, item->item.getId()==100);

如果使用集合,试试这个。

   public static <T> int indexOf(Collection<T> items, Predicate<T> matches) {
        int index = -1;
        Iterator<T> it = items.iterator();
        while (it.hasNext()) {
            index++;
            if (matches.test(it.next())) {
                return index;
            }
        }
        return -1;
    }

与https://github.com/poetix/protonpack 你可以做到,zip:

String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};

List<String> nameList;
Stream<Integer> indices = IntStream.range(0, names.length).boxed(); 

nameList = StreamUtils.zip(indices, stream(names),SimpleEntry::new)
        .filter(e -> e.getValue().length() <= e.getKey()).map(Entry::getValue).collect(toList());                   

System.out.println(nameList);