如何对Hashmap类型的Hashmap进行排序<string,arraylist <string =“”>&gt;按价值?

时间:2015-11-17 06:32:56

标签: java sorting arraylist hashmap

我想按值对以下hashmap进行排序。 Hashmap为Hashmap<String, Arraylist<String>>,其中的数据如下:

924911637601767=[1, John]  
864467483673342=[2, Paul]  
825398867568656=[8, James]  
1034643283235161=[5,Elina]

我想根据计数器值对上述数据进行排序,即1,2,8,5
排序后

924911637601767=[1, John]  
864467483673342=[2, Paul]   
1034643283235161=[5,Elina]  
825398867568656=[8, James]

4 个答案:

答案 0 :(得分:1)

HashMap无法保证订单。

如果您希望按顺序获取列表,则应对HashMap的列表值进行排序。

示例可以在How to sort a HashMap in Java

找到

答案 1 :(得分:1)

  

此课程不保证地图的顺序;特别是,它并不保证订单随时间保持不变。   见http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

换句话说,你想要的东西无法实现。

但是,您可以做的是将Hashmap转换为由每个地图条目元素组成的对象列表。 对象:例如键,名称,数字。 然后,您的对象可以实现java.lang.Comparable,以便根据需要对其进行排序。

请参阅https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

答案 2 :(得分:0)

hashmap抽象数据类型本质上是未排序的。根据您的使用情况,您可以执行以下操作:

import java.util.*;
class Test {
    public static void main(String[] args) {
        Map<String, List<String>> map = new HashMap<>();
        map.put("924911637601767", Arrays.asList("1", "John"));
        map.put("864467483673342", Arrays.asList("2", "Paul"));
        map.put("825398867568656", Arrays.asList("8", "James"));
        map.put("1034643283235161", Arrays.asList("5", "Elina"));

        List<Map.Entry<String,List<String>>> entries = new ArrayList<Map.Entry<String,List<String>>>(map.entrySet());

        Collections.sort(entries, new Comparator<Map.Entry<String,List<String>>>() {
            public int compare(Map.Entry<String,List<String>> l1, Map.Entry<String,List<String>> l2) {
                return l1.getValue().get(0).compareTo(l2.getValue().get(0));
            }
        });

        for (Map.Entry<String,List<String>> e : entries) {
            System.out.println(e.getKey() + " : [" + e.getValue().get(0)
                                          + ", " + e.getValue().get(1) + "]");
        }
    }
}

答案 3 :(得分:0)

如果您对排序顺序感兴趣并且还想保留地图,请使用sortedMap接口。 TreeMap可以是一个选择。

http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html