5

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))
            count++;
    if (count >= threshold )
        throw new IllegalArgumentException("...");
}

I know I can group with collect and groupingBy, and use a filter saying that the operation to apply is contains 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 player in all set of values in a list, using Stream?

2
  • 4
    I don't see any Map in the posted code. Why would you use a Map in a stream-based equivalent? Commented May 2, 2016 at 19:34
  • 1
    Not quite sure what you're trying to achieve here. Can you share an example of such a map and the output you're trying to get for it? Commented May 2, 2016 at 19:42

1 Answer 1

7

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("...");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Would be more efficient with a limit(threshold) after the filter.
@JBNizet I debated whether to put that in, but decided to keep it simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.