Below are chunks of my code from my quiz program in Java. I am trying to read/write high scores to a file and sort the high score table.
public static void main(String[] args) throws IOException {
sort(highscoreTable);
int score1 = 0;
int score2 = 0;
int totalscore = 0;
int NumberofQuestions = 5;
// RECORDS TO STORE QUESTION, ANSWER WOULD BE HERE //
private static void start(int NumberofQuestions, String[] Answers, String[][] questions, int score1, int score2, int totalscore) throws IOException {
// DISPLAYED ON THE HOME SCREEN SO USER CAN CHOOSE WHAT THEY WANT TO DO
System.out.println("[0] Leave\n");
while(true) {
System.out.println("[1] Play");
System.out.println("[2] Highscore");
System.out.print("Enter Choice: ");
String useranswer = scanner.nextLine();
System.out.println();
if (useranswer.equals("1")) {
mainLoop(NumberofQuestions, Answers, questions, score1, score2, totalscore);
} else if (useranswer.equals("2")) {
sort(highscoreTable);
} else if (useranswer.equals("0")) {
try {
save();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
I wanted this bit to be displayed on the screen first, if the user presses 2, i wanted to program to read from the file and show the preious high scores
public static void save() throws IOException {
String aggFileName = "agg-"+String.valueOf("06.txt");
FileWriter fstream = new FileWriter(aggFileName);
BufferedWriter out = new BufferedWriter(fstream);
for (Map.Entry<String, String> entry : highscoreTable.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); //this statement prints out my keys and values
out.write(entry.getKey() + "--" + entry.getValue() + "\n");
System.out.println("Done");
out.flush(); // Flush the buffer and write all changes to the disk
}
out.close(); // Close the file
}
The save method works perfectly and I have no problem with it.
public static void mainLoop(int NumberofQuestions, String[]Answers, String[][] questions, int score1, int score2, int totalscore) throws IOException {
// USER WOULD ANSWER QUESTIONS HERE
addHighscore(name, totalscore);
}
public static void addHighscore(String name, int totalscore) throws IOException {
highscoreTable.put(String.valueOf(totalscore), name);
}
The function here adds the users name and total score to a treemap
public static void highscoreImport(HashMap highscoreTable) throws IOException {
String filePath = "agg-06.txt";
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null)
{
String[] parts = line.split("--", 2);
if (parts.length >= 2)
{
String key = parts[0];
String value = parts[1];
highscoreTable.put(key, value);
} else {
}
}
for (Object key : highscoreTable.keySet())
{
System.out.println(key + "--" + highscoreTable.get(key));
}
reader.close();
}
This is the part I'm having issues with. I want the program to get the information from the file, and now merge it with the data that is coming from the users recent quiz, and then sort the scores (I want a high score table) so that when the users types "2" to see the high score table, it will be in descending order
public static void sort(HashMap highscoreTable) throws IOException {
System.out.println("Before Sorting:");
Set set = highscoreTable.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = new TreeMap<Integer, String>(highscoreTable);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
Here, the list outputted "before" and "after" sorting is the same unsorted list
Sorry for the long read, I would appreciate any help or pointers in fixing this.
Since in the addHighscore method you are doing:
highscoreTable.put(String.valueOf(totalscore), name);
I assume it is a Map<String, String> (both key and value types are String).
But in the sort method you do...
Map<Integer, String> map = new TreeMap<Integer, String>(highscoreTable);
If the types of highscoreTable are correctly defined, the TreeMap instantiation should fail at compiling time. If not, and as the constructor TreeMap(Map) gets ordered by the natural order of its keys (see Javadoc), it is probably ordering it by String order or other. So "111" will be before "12" and other unexpected results. It is a good practice to define the types in all the collections and other generic type classes.
The trouble is with the type of the score. You are inserting the score as a string. A second minor issue is the sort order should be reversed.
Look at the following example:
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("String scores:");
HashMap<String, String> scores = new HashMap<>();
scores.put("12", "John");
scores.put("240", "Mary");
scores.put("14", "Sean");
scores.put("35", "Pat");
sort(scores);
System.out.println();
System.out.println("Integer scores:");
HashMap<Integer,String> integerScores = new HashMap<>();
integerScores.put(12, "John");
integerScores.put(240, "Mary");
integerScores.put(14, "Sean");
integerScores.put(35, "Pat");
sort(integerScores);
}
public static void sort(HashMap highscoreTable) throws IOException {
System.out.println("Before Sorting:");
Set set = highscoreTable.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = new TreeMap<Integer, String>(Collections.reverseOrder()); // Descending
map.putAll(highscoreTable);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
}
This example uses your sort method on 'scores', and 'integerScores'.
Here is the sorted output:
String scores:
35: Pat
240: Mary
14: Sean
12: John
Integer scores:
240: Mary
35: Pat
14: Sean
12: John
You can see in the first sort that 35 comes before 240, because 3 comes before 2. It is doing a string sort. The second sort is by the value of an integer. Once you understand this, it is easy to fix your code.
The original code inserts the key as a String:
highscoreTable.put(key, value);
The key should be an Integer:
highscoreTable.put(Integer.valueOf(key), value);
Also note that the provided answer can be easily run. It includes data (which is simpler that attaching a file), and output. When questions are formatted this way, it is easier to get help.
Related
So I have this program that calculates the sum of all the petshops with the same key but different values. However, now, I would like to calculate the average of each petshop with the same key. I was thinking about using a counter in order to get how many times a petshop is contained in the arraylist. But it does not work. would I need to run another for each loop?
public class AverageCost {
public void calc(ArrayList<Pet> pets) {
Map<String, Double> hm = new HashMap<>();
for (Pet i : pets) {
String name = i.getShop();
// If the map already has the pet use the current value, otherwise 0.
double price = hm.containsKey(name) ? hm.get(name) : 0;
price += i.getPrice();
hm.put(name, price);
}
System.out.println("");
for (String key : hm.keySet()) {
System.out.printf("%s: %s%n", key, hm.get(key));
}
}
What you are asking for is an algorithm to calculate the cumulative moving average without storing the number of terms you have so far accumulated. I don't think this is possible (for example see https://en.wikipedia.org/wiki/Moving_average#Cumulative_moving_average where 'n', the number of terms so far, is required). My suggestion is to use two passes - the first to store the numbers and the second to calculate the averages.
public void calc(List<Pet> pets) {
// First pass
Map<String, List<Double>> firstPass = new HashMap<>();
for (Pet pet : pets) {
String name = pet.getShop();
if (firstPass.containsKey(name)) {
firstPass.get(name).add(pet.getPrice());
} else {
List<Double> prices = new ArrayList<>();
prices.add(pet.getPrice());
firstPass.put(name, prices);
}
}
// Second pass
Map<String, Double> results = new HashMap<>();
for (Map.Entry<String, List<Double>> entry : firstPass.entrySet()) {
Double average = calcAverage(entry.getValue());
results.put(entry.getKey(), average);
// Print results
System.out.printf("%s: %s%n", entry.getKey(), average);
}
}
private double calcAverage(List<Double> values) {
double result = 0;
for (Double value : values) {
result += value;
}
return result / values.size();
}
You can introduce second map for counting or use compound value object in your map to hold both accumulated price and number of pets:
Map<String, PetStatistics> hm = new HashMap<>();
for (Pet i : pets) {
String name = i.getShop();
// If the map already has the pet use the current value, otherwise 0.
PetStatistics stats = hm.get(name);
if (stats == null) {
stats = new PetStatistics(0, 0); // count and price
hm.put(name, stats);
}
stats.addPrice(i.getPrice());
stats.incrementCount();
}
You can use the Collections.frequency to get the number of occurrence and divide the whole sum
for (String key : hm.keySet()) {
int w = Collections.frequency(pets, new Pet(key));
System.out.printf("%s: %s%n", key, hm.get(key)/w);
}
I'm having trouble on how to create a new ordered map that reads a file char by char. Here is the beginning of my program
public class Practice {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the file name to random write: ");
String fileName = keyboard.nextLine();
System.out
.print("Enter nGram length, 1 is like random, 12 is like the book: ");
int nGramLength = keyboard.nextInt();
keyboard.close();
Practice rw = new Practice(fileName, nGramLength);
rw.printRandom(500);
}
private HashMap<String, ArrayList<Character>> all;
private int nGramLength;
private String fileName;
private StringBuilder theText;
private static Random generator;
private String nGram;
public Practice(String fileName, int nGramLength) {
this.fileName = fileName;
this.nGramLength = nGramLength;
generator = new Random();
makeTheText();
setRandomNGram();
setUpMap(); // Algorithm considered during section.
}
private void makeTheText() {
Scanner inFile = null;
try {
inFile = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
theText = new StringBuilder();
while (inFile.hasNextLine()) {
theText = theText.append(inFile.nextLine().trim());
theText = theText.append(' ');
}
}
public void setRandomNGram() {
generator = new Random();
int temp = theText.length() - nGramLength - 1;
int start = generator.nextInt(temp);
nGram = theText.substring(start, start + nGramLength);
}
// Read theText char by char to build a OrderedMaps where
// every possible nGram exists with the list of followers.
// This method need these three instance variables:
// nGramLength theText all
private void setUpMap() {
// TODO: Implement this method
for(int i = 0; i < nGramLength; i++)
{
ArrayList<Character> key = all.get(i);
}
}
// Print chars random characters. Please insert line breaks to make your
// output readable to the poor grader :-)
void printRandom(int howMany) {
// TODO: Implement this method
}
}
I need to work on the last two methods, but I am confused as to how to iterate through a hashmap
You can iterate over a HashMap by iterating over its entrySet(). That will give you both the key and value:
for (Map.Entry<String, ArrayList<Character>> entry : all) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Alternatively you can iterate only over its keySet() or valueSet(), but it sounds as if you want both key and value here.
The answer is that you do not iterator over a map. Maps do not have an iterator because that would make no sense. What would it iterator over the keys the values or both. The solution is turn your keys or values into a collection. You do this with the values method (returns a collection of the values) and keySet method (returns a set of the keys in the map) You can then call those collection's iterator methods.
I have a TreeMap in which I have stored some values. The map is sorted using the values, from highest to lowest. Now I want print out the contents of the TreeMap with their various indices.
If I have the following pairs in the map :
("Andrew", 10),
("John", 5),
("Don",9),
("Rolex", 30),
("Jack", 10),
("Dan",9)
I want to print out:
Rolex, 30 , 1
Jack, 10, 2
Andrew, 10, 2
Dan, 9, 4
Don, 9, 4
John, 5, 6.
This is what I've been trying but it doesn't seem to work well:
/**
*
* #author Andrew
*/
import java.util.*;
public class SortArray {
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>>entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
#Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res!= 0 ? res : 1;
//return e1.getValue().compareTo(e2.getValue());
}
});
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
public void test(){
Map mm = new TreeMap();
mm.put("Andrew", 11);
mm.put("Mbata", 21);
mm.put("Chinedu", 14);
mm.put("Bol", 14);
mm.put("Don", 51);
mm.put("Rolex", 16);
mm.put("Son", 41);
SortedSet newMap = entriesSortedByValues(mm);
Iterator iter = newMap.iterator();
int x = newMap.size();
List names = new ArrayList();
List scores = new ArrayList();
while(iter.hasNext()){
String details = iter.next().toString();
StringTokenizer st = new StringTokenizer(details, "=");
String name = st.nextToken();
names.add(name);
String score = st.nextToken();
scores.add(score);
//System.out.println(name + " Score:" +score + " Position:" + x);
x--;
}
Collections.reverse(names);
Collections.reverse(scores);
int pos = 1;
for(int i = 0; i<names.size();){
try{
int y = i+1;
if(scores.get(i).equals(scores.get(y))){
System.out.print("Name: "+ names.get(i)+"\t");
System.out.print("Score: "+ scores.get(i)+"\t");
System.out.println("Position: "+ String.valueOf(pos));
//pos++;
i++;
continue;
} else{
System.out.print("Name: "+ names.get(i)+"\t");
System.out.print("Score: "+ scores.get(i)+"\t");
System.out.println("Position: "+ String.valueOf(pos++));
}
i++;
} catch(IndexOutOfBoundsException e) {}
}
}
public SortArray(){
test();
}
public static void main(String [] args){
new SortArray();
}
}
First of all, Why are you catching that IndexOutOfBoundsException and doing nothing with it? if you run that you'll get that exception thrown (and I thing you already know it) the problem is in your algorithm inside the last "for" loop. I shouldn't give you the solution, but wth... at least you did some effort to make it run, so this is a more less working version:
import java.util.*;
public class SortArray {
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>>entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
#Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1;
//return e1.getValue().compareTo(e2.getValue());
}
});
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
public void test(){
Map mm = new TreeMap();
mm.put("Andrew", 11);
mm.put("Mbata", 21);
mm.put("Chinedu", 14);
mm.put("Bol", 14);
mm.put("Don", 51);
mm.put("Rolex", 16);
mm.put("Son", 41);
SortedSet newMap = entriesSortedByValues(mm);
Iterator iter = newMap.iterator();
int x = newMap.size();
List names = new ArrayList();
List scores = new ArrayList();
while(iter.hasNext()){
String details = iter.next().toString();
StringTokenizer st = new StringTokenizer(details, "=");
String name = st.nextToken();
names.add(name);
String score = st.nextToken();
scores.add(score);
//System.out.println(name + " Score:" +score + " Position:" + x);
x--;
}
Collections.reverse(names);
Collections.reverse(scores);
int pos;
int posBis = 0;
String lastScore = "";
for(int i = 0; i<names.size(); i++){
System.out.print("Name: "+ names.get(i)+"\t");
System.out.print("Score: "+ scores.get(i)+"\t");
if(i == 0 || !lastScore.equals(scores.get(i))) {
pos = i + 1;
posBis = pos;
} else {
pos = posBis;
}
System.out.println("Position: "+ String.valueOf(pos));
lastScore = (String)scores.get(i);
}
}
public SortArray(){
test();
}
public static void main(String [] args){
new SortArray();
}
}
Your SortedSet is the wrong way to go about this. You can see in your Comparator that it gets a bit messy when both values have to be looked up by the same key then you've got this messy (and incorrect) return res != 0 ? res : 1 (the 1 should really be e1.getKey().compareTo(e2.getKey()) rather than always returning 1).
A better way to go about this would be to just sort the keys yourself in a List, rather than creating a separate SortedSet. This way you don't have to worry about duplicate sorting values.
You can also abstract out the Comparator stuff a little, to make it more reusable in other code later, if you need it.
import java.util.*;
public class PrintSomething {
public static <T extends Comparable<T>> Comparator<T> reverseComparator(final Comparator<T> oldComparator) {
return new Comparator<T>() {
#Override
public int compare(T o1, T o2) {
return oldComparator.compare(o2, o1);
}
};
}
public static <K,V extends Comparable<V>> Comparator<K> keyedComparator(final Map<K,V> lookup) {
return new Comparator<K>() {
#Override
public int compare(K o1, K o2) {
return lookup.get(o1).compareTo(lookup.get(o2));
}
};
}
public static void main(String[] args) {
Map<String, Integer> mm = new HashMap<>();
mm.put("Andrew", 10);
mm.put("John", 5);
mm.put("Don", 9);
mm.put("Rolex", 30);
mm.put("Jack", 10);
mm.put("Dan", 9);
Comparator<String> comparator = reverseComparator(keyedComparator(mm));
List<String> keys = Arrays.asList(mm.keySet().toArray(new String[mm.size()]));
//Collections.sort(keys); // optional, if you want the names to be alphabetical
Collections.sort(keys, comparator);
int rank = 1, count = 0;
Integer lastVal = null;
for (String key : keys) {
if (mm.get(key).equals(lastVal)) {
count++;
} else {
rank += count;
count = 1;
}
lastVal = mm.get(key);
System.out.println(key + ", " + mm.get(key) + ", " + rank);
}
}
}
In general things like SortedSet make more sense when you need to keep the data itself sorted. When you just need to process something in a sorted manner one time they're usually more trouble than they're worth. (Also: is there any reason why you're using a TreeMap? TreeMaps sort their keys, but not by value, so in this case you're not taking advantage of that sorting. Using a HashMap is more common in that case.)
You do a lot of work with the iterator, calling toString(), then splitting the results. And your Comparator is extra work too. Stay with a Map on both sides - you can use keys() and values() more directly, and let Java do the sorting for you. Most of your above code can be replaced with: (for clarity, I changed your name "mm" to "originalMap")
Map<Integer, String> inverseMap = new TreeMap<Integer, String>();
for (Map.Entry<String, Integer> entry : originalMap.entrySet()) {
inverseMap.put(entry.getValue(), entry.getKey());
}
Now, iterate over inverseMap to print the results. Note that if a count does exist twice in originalMap, only one will be printed, which is what you want. But which one gets printed left as an exercise for the reader :-). You might want to be more specific on that.
EDIT ADDED: If you do want to print out duplicate scores, this is not what you want. The original post I read said to skip if they were the same, but I don't see that after the edits, so I'm not sure if this is what OP wants.
I have a list of input strings of the form "code-marks"
For example,
1001-40
1002-54
1003-23
1001-45
1004-60
Expected output:
1004-60
1002-54
1001-45
1003-23
If the values are repeated (like 1001) the latest is used and also need to be sorted.
My first bet was to use TreeMap but it would pose a problem of sorting based on values which is impossible.
Scanner in = new Scanner(System.in);
SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return(j.compareTo(i));
}
});
int i=0;
while(i<5)
{
String[] s = in.next().split("\\-");
map.put(Integer.parseInt(s[0]),Integer.parseInt(s[1]));
i++;
}
// Get a set of the entries
Set set = map.entrySet();
// Get an iterator
Iterator itr = set.iterator();
// Display elements
while(itr.hasNext()) {
Map.Entry me = (Map.Entry)itr.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
What is the best approach to this situation?
I stole code from the link #Pshemo posted and then setup your data as part of the main along with a simulated unit test. Code first then output.
Code
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;
/**
* Group of code marks
*/
public class CodeMarks {
/**
* Keep track of the most recently added suffix (value) by prefix (key)
*/
HashMap<Integer, Integer> codeMarks = new HashMap<Integer, Integer>();
/**
* Add a code mark (i.e. ####-##) to the group.
* If same prefix already exists overwrite.
*
* #param codeMark
*/
public void add(String codeMark) {
// add some validation here
String[] pieces = codeMark.split("\\-");
Integer prefix = Integer.parseInt(pieces[0]);
Integer suffix = Integer.parseInt(pieces[1]);
codeMarks.put(prefix, suffix);
}
/**
* Sort code marks in descending suffix order.
*/
Comparator<Integer> comparator = new Comparator<Integer>() {
#Override
public int compare(Integer prefixA, Integer prefixB) {
Integer suffixA = codeMarks.get(prefixA);
Integer suffixB = codeMarks.get(prefixB);
if (suffixB.equals(suffixA))
return prefixB.compareTo(prefixA);
else
return suffixB.compareTo(suffixA);
}
};
/**
* Output all code marks in descending suffix order
*/
public String toString() {
TreeMap<Integer,Integer> sorted_map = new TreeMap<Integer,Integer>(comparator);
sorted_map.putAll(codeMarks);
StringBuffer output = new StringBuffer();
for (Integer prefix : sorted_map.keySet()) {
Integer suffix = sorted_map.get(prefix);
output.append(prefix + "-" + suffix + "\n");
}
return output.toString();
}
public static void main(String args[]) {
CodeMarks cm = new CodeMarks(){{
add("1001-40");
add("1002-54");
add("1003-23");
add("1001-45");
add("1004-60");
}};
String expected =
"1004-60\n" +
"1002-54\n" +
"1001-45\n" +
"1003-23\n";
String actual = cm.toString();
System.out.println(actual);
System.out.println("actual.equals(expected): " + actual.equals(expected));
}
}
Output
1004-60
1002-54
1001-45
1003-23
actual.equals(expected): true
I would simply use a HashMap<Code, CodeMark> to eliminate duplicate codes, then put all the values inside a List<CodeMark>, and sort this list by mark in descending order.
You can use HashMap<Integer,Integer> simply and then sort that according to their values:
public LinkedHashMap<Integer,Integer> sortHashMapByValues(HashMap<Integer,Integer> passedMap) {
List<Integer> mapKeys = new ArrayList<Integer>(passedMap.keySet());
List<Integer> mapValues = new ArrayList<Integer>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<Integer,Integer> sortedMap =
new LinkedHashMap<Integer,Integer>();
Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
int key = (Integer)keyIt.next();
int comp1 = (Integer)passedMap.get(key);
int comp2 = (Integer)val;
if (comp1 == comp2){
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put(key,(Integer) val);
break;
}
}
}
return sortedMap;
}
This simple game asks for the number of the players and their names and counts their score.How can i get the player with the highest score?
main:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<String,Integer> players= new HashMap<String,Integer>();
System.out.printf("Give the number of the players: ");
int numOfPlayers = scanner.nextInt();
for(int k=1;k<=numOfPlayers;k++)
{
System.out.printf("Give the name of player %d: ",k);
String nameOfPlayer= scanner.next();
players.put(nameOfPlayer,0);//score=0
}
//This for finally returns the score
for(String name:players.keySet())
{
System.out.println("Name of player in this round: "+name);
//::::::::::::::::::::::
//::::::::::::::::::::::
int score=players.get(name)+ p.getScore();;
//This will update the corresponding entry in HashMap
players.put(name,score);
System.out.println("The Player "+name+" has "+players.get(name)+" points ");
}
}
This what i tried myself:
Collection c=players.values();
System.out.println(Collections.max(c));
You can use Collections.max() to get the maximum value of the Collection of hashmap entries obtained by HashMap.entrySet() with custom comparator for comparing values.
Example:
HashMap<String,Integer> players= new HashMap<String,Integer>();
players.put("as", 10);
players.put("a", 12);
players.put("s", 13);
players.put("asa", 15);
players.put("asaasd", 256);
players.put("asasda", 15);
players.put("asaws", 5);
System.out.println(Collections.max(players.entrySet(),new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}));
You can modify above code to best meet your condition.