Detect duplicated groups in stream

后端 未结 3 1695
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 10:32

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         


        
3条回答
  •  清歌不尽
    2021-02-20 11:18

    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.

提交回复
热议问题