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
In my opinion this problem doesn't fit the Stream API
at all but I was curious how this could be implemenented (however in a performant way).
The problem is that you have to keep track of seen elements and the whole test should have a short-circuit behaviour. So I came up with this solution (without Streams
):
public static boolean hasUniqueGroups(int[] arr) {
Objects.requireNonNull(arr);
Set seen = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
if (i == 0 || arr[i] != arr[i - 1]) {
if (!seen.add(arr[i])) {
return false;
}
}
}
return true;
}
The next step is to introduce the Stream API
and the solution looks like this:
public static boolean hasUniqueGroups(int[] arr) {
Objects.requireNonNull(arr);
Set seen = new HashSet<>();
return IntStream.range(0, arr.length)
.filter(i -> i == 0 || arr[i] != arr[i - 1])
.mapToObj(i -> arr[i])
.allMatch(seen::add);
}
Note: In order to parallelize this Stream
you should use a thread-safe Set
.