简体   繁体   中英

How do you sort a hash map table with values and keys in Java

How do you sort out a hash maps numerically and then alphabetically ? input:

anna , 1
jane , 2
amy  , 3

required output:

amy  , 3
anna , 1
jane , 2

Map<String, Integer> myDictionary = new HashMap<String, Integer>();

This is how i sort it out atm but it only sorts it alphabetically

Set<String> sorted = new TreeSet<String>(); 

sorted.addAll(myDictionary.keySet());

for(String key: sorted){

    System.out.println(key  + " -" + myDictionary.get(key));

}

You can convert the Map into a List, sort the List by Comparator and put the sorted list back to a Map.

Look into this for reference Sort a Map by Values

Here is a rough sketch of how you'd probably want to work with

class Person 
{
   public String name;
   public int point;
   //others methods
}
class SortName implements Comparator<Person>
{
   public int compare(Person one, Person two)
   {return comparison of name}
}

class SortPoint implements Comparator<Person>
{
   public int compare(Person one, Person two)
   {return comparison of point}
}

//usage
List.sort(person, new SortName());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM