【问题标题】:How do you sort a hash map table with values and keys in Java如何在 Java 中使用值和键对哈希映射表进行排序
【发布时间】:2014-05-13 02:20:00
【问题描述】:

如何按数字和字母顺序排列散列映射? 输入:

anna , 1
jane , 2
amy  , 3

需要的输出:

amy  , 3
anna , 1
jane , 2

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

这是我在 atm 中排序的方式,但它只按字母顺序排序

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

sorted.addAll(myDictionary.keySet());

for(String key: sorted){

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

}

【问题讨论】:

标签: java sorting hashmap


【解决方案1】:

您可以将 Map 转换为 List,通过 Comparator 对 List 进行排序,然后将排序后的列表放回 Map。

查看此内容以供参考Sort a Map by Values

【讨论】:

    【解决方案2】:

    这是您可能希望如何使用的粗略草图

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 2011-04-04
      • 2021-12-23
      • 2012-05-01
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多