简体   繁体   English

使用 java stream API 检查列表元素是否是整数的连续范围

[英]Check if list elements are a continuous range of integers using java stream API

Given var ns = List.of(1,2,3,4) How can one check if the list elements are consecutive using java stream API给定var ns = List.of(1,2,3,4)如何使用 java stream API 检查列表元素是否连续

It can be done using the following loop:可以使用以下循环来完成:

for (var i = 1; i <= ns.size() - 1; i++) {
    if (ns.get(i) - ns.get(i - 1) != 1)
        return false;
}
return true;

How can it be done using ns.stream.reduce or other stream method?如何使用ns.stream.reduce或其他 stream 方法来完成?

There are many ways to solve this, I would like to create an ordered list and compare it with the initial one, for example:有很多方法可以解决这个问题,我想创建一个有序列表并将其与初始列表进行比较,例如:

List<Integer> ints = IntStream.iterate(ns.get(0), i -> i + 1)
        .limit(ns.size()).boxed()
        .collect(Collectors.toList());
return ns.equals(ints);

Or also you can use:或者您也可以使用:

AtomicInteger ai = new AtomicInteger(); // used to generate indexes(0, 1, 2...)
return IntStream.iterate(ns.get(0), i -> i + 1)
        .limit(ns.size())
        .allMatch(i -> i == ns.get(ai.getAndIncrement()));

You could approach this problem as mapping the difference between two adjacent elements in list and if any difference is not equal to 1, this isn't a consecutive list.您可以通过映射列表中两个相邻元素之间的差异来解决此问题,如果任何差异不等于 1,则这不是连续列表。 One of the ways to do this is this做到这一点的方法之一是

    final var ns = List.of(1, 2, 3, 4);
    IntStream.range(0, ns.size() - 1)
        .mapToLong(operand -> ns.get(operand + 1) - ns.get(operand))
        .anyMatch(value -> value != 1);

Even though you haven't mentioned that the input list could be consecutive in ascending or descending order, the below code could be used to handle both scenarios using Collectors.reducing .即使您没有提到输入列表可以按升序或降序连续,但下面的代码可用于使用Collectors.reducing处理这两种情况。 (Might not be as optimal as @YCF_L's solution) (可能不如@YCF_L 的解决方案最佳)

AtomicInteger i = new AtomicInteger(list.get(0));
Function<AtomicInteger, Integer> f = a -> (list.get(0) < list.get(1)) 
    ? i.getAndIncrement()
    : i.getAndDecrement();

return list.stream()
           .collect(Collectors.groupingBy(Function.identity(),
                                          Collectors.reducing(0, (a, b) -> b - f.apply(i))))
           .values()
           .stream()
           .allMatch(n -> n == 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM