Last active
January 25, 2021 12:35
-
-
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
This file contains 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
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); | |
} | |
} |
This file contains 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
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