测试列表是否仅包含给定范围内的值的有效方法是什么?
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/