Skip to content

Instantly share code, notes, and snippets.

@ItsCosmas
Last active January 25, 2021 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ItsCosmas/b7a872af65252ec07ec99dcf85caeb73 to your computer and use it in GitHub Desktop.
Save ItsCosmas/b7a872af65252ec07ec99dcf85caeb73 to your computer and use it in GitHub Desktop.
Sololearn Various Ways to Iterate a HashMap and outputs the name of the player with the maximum points. https://www.sololearn.com/learning/eom-project/1068/972
package com.cozy;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class BowlingHashMap {
HashMap<String, Integer> players;
BowlingHashMap() {
players = new HashMap<String, Integer>();
}
public void addPlayer(String name, int p) {
players.put(name, p);
}
String maxName;
int current;
int max = 0;
public void getWinner(){
// for Loop
// for (Map.Entry<String, Integer> set : players.entrySet()) {
// current = set.getValue();
// if(current > max){
// max = current;
// maxName = set.getKey();
// }
// }
// forEach Loop
players.forEach((key,value) -> {
current = value;
if(current > max){
max = current;
maxName = key;
}
});
// Using an iterator
// Setting up iterator.
// Iterator<Map.Entry<String, Integer>> it = players.entrySet().iterator();
// // iterating every set of entry in the HashMap.
// while (it.hasNext()) {
// Map.Entry<String, Integer> set = (Map.Entry<String, Integer>) it.next();
// current = set.getValue();
// if(current > max){
// max = current;
// maxName = set.getKey();
// }
// }
System.out.println(maxName);
}
}
package com.cozy;
import java.util.Scanner;
public class Main {
public static void main(String[ ] args) {
BowlingHashMap game = new BowlingHashMap();
Scanner sc = new Scanner(System.in);
for(int i=0;i<3;i++) {
String input = sc.nextLine();
String[] values = input.split(" ");
String name = values[0];
int points = Integer.parseInt(values[1]);
game.addPlayer(name, points);
}
game.getWinner();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment