dabadaba dabadaba - 2 years ago 137
Java Question

Java 8 streams: count values

I am trying to get the number of ocurrences of an object in the set of values in a list using Java 8 streams, but I can't get the hang of it yet.

This is what I am trying to do:

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

I know I can group with
, and use a filter saying that the operation to apply is
with the new method reference operator. But I am still too green with these new Java 8 features and cannot put it all together.

So how could I extract the number of ocurrences of
in all set of values in a list, using Stream?

Answer Source

Lambda expressions can help separate the different bits of logic and then compose them together.

As I understand from your code, you are testing players for whether they are contained in at least threshold elements of matches. We can write the test logic as follows:

Predicate<Player> illegalTest = player -> matches.stream()
        .filter(m -> m.contains(player))
        .count() >= threshold;

Then we want to apply this test to see if any of the players matches:

boolean hasIllegal = match.stream().anyMatch(illegalTest);

And finally:

if (hasIllegal) {
    throw new IllegalArgumentException("...");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download