Getting the Set with the most elements nested in a HashMap using Java Streams

Bratislav B. :

So here is the situation: I need to register people's vote for certain dates. In short, a date is proposed and people vote for the date they want.

The data structure is the following:

private HashMap<LocalDateTime, Set<Vote>> votes;

A vote is:

public class Vote {
    private String name;
    private VoteType vote;

    public Vote(String name, VoteType vote) {
        super();
        this.name = name;
        this.vote = vote;
    }
}

Where VoteType is just an enum:

public enum VoteType {YES, NO, MAYBE}

Now I already made a stream that returns the amount of votes for the availability (VoteType):

public Map<LocalDateTime, Integer> voteCount(VoteType targetVote) {
    return this.votes.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new Integer(
            e.getValue().stream().filter(v -> v.getVote() == targetVote).collect(Collectors.toList()).size())));
}

So my question is: How can I get, using Java Streams, the date that got the most 'YES'.

/* Returns the date that got the most 'YES' votes */
public LocalDateTime winningDate() {
    // TODO
}

Thank you for the help!

Ousmane D. :

So my question is: How can I get, using Java Streams, the date that got the most 'YES'.

This is going to be a lengthy one...

  1. we need to get to a position where we have a Stream<LocalDateTime> so we can later group by date applying a counting downstream collector to get the number of votes on that specific date and we can accomplish this structure via flatMap.
  2. we need to retain only the objects where the vote type is YES
  3. we group the results by the date and have the values as the number of YES votes on that specific date.
  4. we stream over the entrySet and find the max date by vote

Code:

/* Returns the date that got the most 'YES' votes */
public Optional<LocalDateTime> getWinningDate() {
    return votes.entrySet() // Set<Entry<LocaleDateTime, Set<Vote>>
            .stream() // Stream<Entry<LocaleDateTime, Set<Vote>>
            .flatMap(e -> e.getValue().stream().filter(a -> a.getVote() == VoteType.YES)
                         .map(x -> e.getKey())) // Stream<LocalDateTime>
           .collect(groupingBy(Function.identity(), counting())) // Map<LocaleDateTime, Long>
           .entrySet() // Set<Entry<LocaleDateTime, Long>>
           .stream() // Stream<Entry<LocaleDateTime, Long>>
           .max(Comparator.comparingLong(Map.Entry::getValue)) // Optional<Entry<LocaleDateTime, Long>>
           .map(Map.Entry::getKey); // Optional<LocalDateTime>
}
  • note that I've changed the method return type to Optional<LocaleDateTime>, I could have returned .map(Map.Entry::getKey).orElse(null) thus you've be able to maintain your current method return type of LocalDateTime but that just feels bad and so I've decided to defer the decision upon what to do in the "no value case" to the client.
  • I've changed the method name to getWinningDate to enhance readability.

As for dealing with Optional<T>, in your case, if you want to have a null value in the case of getWinningDate returning an empty Optional, you can unwrap it safely as:

LocalDateTime winningDate = getWinningDate().orElse(null);

or if you want to provide a default date:

LocalDateTime winningDate = getWinningDate().orElse(defaultDate);

or if you're sure there will always be a result then simply call get().

LocalDateTime winningDate = getWinningDate().get();

etc..

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=37090&siteId=1