Erez Ben Harush
Erez Ben Harush

Reputation: 867

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?

Upvotes: 0

Views: 1547

Answers (3)

Gautham M
Gautham M

Reputation: 4935

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

Upvotes: 0

mihajlo
mihajlo

Reputation: 71

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

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60036

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

Upvotes: 2

Related Questions