user3407267
user3407267

Reputation: 1634

How to Check if a List contains elements only from a given range JAVA?

What is the efficient way to test whether a list has values which are only from a given range?

Eg. List = 1,6,0,4556 
Range = 0 - 10
so here isValid(list) = false // 4556 is not in the range

Eg. List = 188,8,0,-90 
Range = 0 - 10
so here isValid(list) = false // -90 and 188 are not in the range

Eg. List = 1 ,8,0 
Range = 0 - 10
so here isValid(list) = true 

Upvotes: 1

Views: 3443

Answers (2)

Donald Raab
Donald Raab

Reputation: 6686

Using Java 8 primitive IntStream:

IntPredicate contains = value -> 0 <= value && value <= 10;
Assert.assertFalse(
        IntStream.of(1, 6, 0, 4556).allMatch(contains));
Assert.assertFalse(
        IntStream.of(188, 8, 0, -90).allMatch(contains));
Assert.assertTrue(
        IntStream.of(1, 8, 0).allMatch(contains));

Using Eclipse Collections primitive IntList:

IntPredicate contains = IntInterval.zeroTo(10)::contains;
Assert.assertFalse(
        IntLists.mutable.with(1, 6, 0, 4556).allSatisfy(contains));
Assert.assertFalse(
        IntLists.mutable.with(188, 8, 0, -90).allSatisfy(contains));
Assert.assertTrue(
        IntLists.mutable.with(1, 8, 0).allSatisfy(contains));

In both cases here the int values will not be boxed as Integers, which may make it more efficient.

Note: I am a committer for Eclipse Collections.

Upvotes: 2

Jacob G.
Jacob G.

Reputation: 29680

I originally mentioned Guava's RangeSet, but I'm not sure if it's applicable to Lists with arbitrary elements.

Anyway, you can use the following with Java 8:

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 6, 0, 4556);

    System.out.println(inRange(list, 0, 10));
}

private static boolean inRange(List<Integer> list, int min, int max) {
    return list.stream().allMatch(i -> i >= min && i <= max);
}

>> false

Upvotes: 2

Related Questions