I want to ensure that all numbers in the list are grouped together. Let me explain this on examples:
{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
Here's how I obtain the stream:
IntStream.of(numbers)
...
Now I need to pass or return true for "OK" examples and throw AssertionError
or return false on "Bad" examples. How can I do that using Stream API?
Here's my current solution with additional Set
created:
Set<Integer> previousNumbers = new HashSet<>();
IntStream.of(numbers)
.reduce(null, (previousNumber, currentNumber) -> {
if (currentNumber == previousNumber) {
assertThat(previousNumbers).doesNotContain(currentNumber);
previousNumbers.add(currentNumber);
}
return currentNumber;
}
);