Last active
September 20, 2022 11:19
-
-
Save jsbonso/3c12b89ffe2c45589a0af5e8907bdf9c to your computer and use it in GitHub Desktop.
Counts the number of votes for each Candidates and shows the winner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: