2

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));

}
ipalibowhyte
  • 1,553
  • 2
  • 22
  • 34
  • A previous answer of mine: http://stackoverflow.com/a/22672888/2864740 - 1) define a `Comparator`, 2) Don't use a Set for this, even if a SortedSet. (It even has an example of "sort by .. then by ..", see how the names are also compared in case of a tie on wins.) – user2864740 Apr 02 '14 at 03:21
  • Also, ref. perhaps: http://stackoverflow.com/a/3074324/2864740 – user2864740 Apr 02 '14 at 03:25
  • You don't sort a HashMap. You can sort the keys of the HashMap and then access the HashMap by sorted key, or you can use a LinkedHashMap and somehow get your entries into the desired order. But a standard Map or Set has no defined order. – Hot Licks Apr 02 '14 at 04:03

2 Answers2

1

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

Gundamaiah
  • 780
  • 2
  • 6
  • 30
1

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());
user3462253
  • 146
  • 1
  • 1
  • 5