检测流中的重复组 [英] Detect duplicated groups in stream

查看:66
本文介绍了检测流中的重复组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保列表中的所有数字都组合在一起。让我用例子解释一下:

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)
    ...

现在我需要为OK示例传递或返回true并抛出 AssertionError 或在坏示例中返回false。如何使用Stream API执行此操作?

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?

这是我当前的解决方案,其中包含 Set

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;
                }
        );


推荐答案

使用我的免费StreamEx 库:

IntStreamEx.of(numbers).boxed().runLengths().toMap();

此代码将抛出 IllegalStateException 如果有重复小组。

This code will throw IllegalStateException if there are repeating groups.

这里 runLengths() 方法。它折叠相等的相邻元素,用 Map.Entry 替换它们,其中key是输入元素,value是重复的数量。最后使用 toMap(),这是 .collect(Collectors.toMap(Entry :: getKey,Entry :: getValue))的快捷方式。我们使用的事实是 .toMap()在重复键时抛出 IllegalStateException (除非提供了自定义mergeFunction)。

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.

这篇关于检测流中的重复组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆