我想确保列表中的所有数字都分组在一起。让我用例子来解释这一点:
{1, 1, 1, 2, 2} // OK, two distinct groups
{1, 1, 2, 2, 1, 1} // Bad, two groups with "1"
{1, 2, 3, 4} // OK, 4 distinct groups of size 1
{1, 1, 1, 1} // OK, 1 group
{3, 4, 3} // Bad, two groups with "3"
{99, -99, 99} // Bad, two groups with "99"
{} // OK, no groups
这是我获取流的方法:
IntStream.of(numbers)
...
现在我需要为“OK”示例传递或返回 true 并抛出AssertionError
或在“Bad”示例上返回 false。我如何使用 Stream API 来做到这一点?
这是我当前的解决方案以及附加的Set
创建:
Set<Integer> previousNumbers = new HashSet<>();
IntStream.of(numbers)
.reduce(null, (previousNumber, currentNumber) -> {
if (currentNumber == previousNumber) {
assertThat(previousNumbers).doesNotContain(currentNumber);
previousNumbers.add(currentNumber);
}
return currentNumber;
}
);