简体   繁体   English

如何在Java中使用值和键对哈希映射表进行排序

[英]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 这是我对atm进行排序的方式,但仅按字母顺序对其进行排序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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