java - 如何检查列表是否仅包含给定范围 JAVA 中的元素?

标签 java list 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 

最佳答案

使用 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 值都不会装箱为整数,这可能会提高效率。

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

关于java - 如何检查列表是否仅包含给定范围 JAVA 中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43648759/

相关文章:

java - Jenkins:在没有描述符的类上使用 validateButton

java - 初始化要在循环内重复使用的 String 的内存有效方法

java - 使用 spring data mongodb 存储库添加可选查询参数

python - 有没有办法只搜索元组列表中的第一个坐标?

android - 设置和显示动态列表

java - JVM 上的浮点运算会在所有平台上给出相同的结果吗?

python - 按字典值对字典列表进行排序

python - 是否可以在Python中的Range函数运行时更改它的值?

performance - 测试两个范围是否重叠的最有效方法是什么?

python - 确定列值是否在基于另一列的条件范围之间