简体   繁体   中英

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

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?

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. 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 . (Might not be as optimal as @YCF_L's solution)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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