Skip to content
Advertisement

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

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?

Advertisement

Answer

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()));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement