繁体   English   中英

如何检查List是否只包含来自给定范围JAVA的元素?

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

测试列表是否具有仅来自给定范围的值的有效方法是什么?

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 

使用Java 8原语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));

使用Eclipse Collections原语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));

在这两种情况下,int值都不会被装箱为Integers,这可能会提高效率。

注意:我是Eclipse Collections的提交者。

我最初提到了Guava的RangeSet ,但我不确定它是否适用于具有任意元素的List

无论如何,您可以在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

暂无
暂无

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

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