Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Last active September 20, 2022 11:19
Show Gist options
  • Save jsbonso/3c12b89ffe2c45589a0af5e8907bdf9c to your computer and use it in GitHub Desktop.
Save jsbonso/3c12b89ffe2c45589a0af5e8907bdf9c to your computer and use it in GitHub Desktop.
Counts the number of votes for each Candidates and shows the winner
import java.util.*;
import java.util.concurrent.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class VoteCount{
public static void main(String[] args) {
// Populate Data
String[] votes = {"Jon", "Bonso", "Stacey", "Jon", "Bonso", "Stacey", "Jon", "Bonso", "Brie", "Jon", "Bonso", "Jon"};
System.out.println("Votes: \t\t\t\t" + Arrays.toString(votes));
System.out.println("The winner: " + getCandidateWithTheHighestVote(votes));
}
public static String getCandidateWithTheHighestVote(String[] votes){
// 1. Populate the Map
ConcurrentMap<String, Integer> leaderboard = new ConcurrentHashMap<String, Integer>();
for (String candidate : votes) {
leaderboard.putIfAbsent(candidate, 0);
leaderboard.replace(candidate, leaderboard.get(candidate) + 1);
}
System.out.println("Populated Map (Unsorted): \t" + leaderboard.toString());
// 2. Arrange from Highest to Lowest
Map<String, Integer> sortedMap =
leaderboard.entrySet().stream()
// .sorted(Entry.comparingByValue()) // Ascending
.sorted(Entry.comparingByValue(Comparator.reverseOrder())) // Descending
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new)); // order by insert
System.out.println("Populated Map (Sorted): \t" + sortedMap.toString() + "\n");
System.out.println("1st : " + sortedMap.keySet().toArray()[0]
+ "\t | # of Votes: " + sortedMap.values().toArray()[0]);
System.out.println("2nd : " + sortedMap.keySet().toArray()[1]
+ "\t | # of Votes: " + sortedMap.values().toArray()[1]);
System.out.println("3rd : " + sortedMap.keySet().toArray()[2]
+ "\t | # of Votes: " + sortedMap.values().toArray()[2]);
return String.valueOf(sortedMap.keySet().toArray()[0]);
}
}
@jsbonso
Copy link
Author

jsbonso commented May 30, 2018

Result:

Votes: [Ana, Lorna, Fe, Ana, Lorna, Fe, Ana, Lorna, Fe, Ana, Lorna, Ana]
Populated Map (Unsorted): {Lorna=4, Ana=5, Fe=3}
Populated Map (Sorted): {Ana=5, Lorna=4, Fe=3}

1st : Ana | # of Votes: 5
2nd : Lorna | # of Votes: 4
3rd : Fe | # of Votes: 3

@jsbonso
Copy link
Author

jsbonso commented Sep 20, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment