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
Using my free StreamEx library:
IntStreamEx.of(numbers).boxed().runLengths().toMap();
This code will throw IllegalStateException
if there are repeating groups.
Here runLengths() method is used. It collapses equal adjacent elements replacing them with Map.Entry
where key is the input element and value is the number of repeats. Finally toMap()
is used which is a shortcut for .collect(Collectors.toMap(Entry::getKey, Entry::getValue))
. We are using the fact that .toMap()
throws IllegalStateException
when keys repeat (unless custom mergeFunction is supplied).
As a free bonus on successful execution you will have a map where keys are input elements and values are lengths of series.