I'm looking to use a String[] of logs detailing users who have connected to a website to print out in descending order the amount of times each user has connected. Each log contains some information but the unique userID is always within the first index of the array.
I'm trying to go through the array in O(N) time, calculate how many times each user has connected by adding them to a HashMap, then print out the connected users in descending order based on how many times they have connected. How can this be done? I'm open to switching up my entire implementation if there is an easier way to track the amount of occurrences within the String[]. I have attached an example below:
// Connection logs in the form [Username, Location, time]
String[] logs = {
"name1,Chicago,8pm",
"name2,New York,6pm",
"name3,Los Angeles,2am",
"name1,Chicago,3pm",
"name1,Chicago,12pm",
"name4,Miami,3pm"
"name4,Miami,6pm"
};
printConnections(logs);
/* Desired output:
name1: 3
name2: 2
name4: 2
name3: 1
*/
public static void printConnections(String[] connections){
HashMap<String, Integer> hashmap = new HashMap<String, Integer>();
for (String log : connections){
String name = log.split(",")[0];
if (hashmap.containsKey(name)){
hashmap.replace(name, hashmap.get(name) + 1);
}
else{
hashmap.put(name, 1);
}
}
// Print all key/values in descending order of value
}