Counting votes for candidates in a category and region With the following code, I want to count the Vote objects from a collection, filtering on one of their fields, Candidate.

I have the feeling that I can get this done much more efficiently.

// Get all votes from the database
Collection&lt;Vote&gt; votes = getVotesFromCategoryAndRegion(c, r);

// Filter distinct candidates
Collection&lt;Candidate&gt; candidates = votes
            .stream()
            .map(Vote::getCandidate)
            .distinct()
            .collect(Collectors.toList());


List&lt;VoteResult&gt; results = new ArrayList&lt;&gt;();


// If vote.candidate == candidate, candidates's vote counter ++
for (Candidate currentCandidate : candidates) {
      int currentVoteCount = 0;
      for (Vote v : votes)
          if (v.getCandidate().equals(currentCandidate))
              currentVoteCount++;

      results.add(new VoteResult(currentCandidate, currentVoteCount));
    }


    Collections.sort(results);
    return results;


If you have any suggestions, please tell.
can get this done much more efficiently.


Yes, I agree.

If C candidates each receive an average of V votes (total of C * V votes cast), then your complexity is quadratic in number of candidates: O(C * C * V).

There's nothing so bad about making a pair of linear passes, to accumulate candidates and then votes.

But there's no need, you can make a single pass to do both. Create a HashMap, iterate over all votes, probe the map to see if you should add a zero entry for a new candidate, and then increment the entry so you'll have vote totals at the end.