Java 8流:计数值

dab*_*aba 4 java lambda java-8 java-stream

我试图使用Java 8流来获取列表中值集合中对象的发生次数,但我还是无法掌握它.

这就是我想要做的:

int threshold = 5;
for (Player player : match) { // match is a Set<Player>
    int count = 0;
    for (Set<Player> existingMatch : matches)
        if (existingMatch.contains(player))
            count++;
    if (count >= threshold )
        throw new IllegalArgumentException("...");
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用collect和分组groupingBy,并使用过滤器说要应用的操作是contains使用新方法引用运算符.但是我对这些新的Java 8功能仍然太过绿色,并且无法将它们整合在一起.

那么我如何使用Stream 提取列表player所有值集的出现次数?

Mis*_*sha 6

Lambda表达式可以帮助分离不同的逻辑位,然后将它们组合在一起.

正如我从你的代码中理解的那样,你正在测试玩家是否至少包含在threshold元素中matches.我们可以编写测试逻辑如下:

Predicate<Player> illegalTest = player -> matches.stream()
        .filter(m -> m.contains(player))
        .count() >= threshold;
Run Code Online (Sandbox Code Playgroud)

然后我们想要应用此测试来查看是否有任何玩家匹配:

boolean hasIllegal = match.stream().anyMatch(illegalTest);
Run Code Online (Sandbox Code Playgroud)

最后:

if (hasIllegal) {
    throw new IllegalArgumentException("...");
}
Run Code Online (Sandbox Code Playgroud)

  • 在过滤器之后使用"limit(threshold)"会更有效. (4认同)