java arraylist HashMap如何排序?

时间:2013-02-04 07:23:19

标签: java map arraylist hashmap

如何排序数组?

之前

{"A"=1, "B"=1, "C"=3}, 
{"A"=1, "B"=1, "C"=2},
{"A"=1, "B"=11, "C"=2},
{"A"=1, "B"=2, "C"=2},
{"A"=1, "B"=1, "C"=11}

{"A"=1, "B"=1, "C"=2},
{"A"=1, "B"=1, "C"=3},
{"A"=1, "B"=1, "C"=11},
{"A"=1, "B"=2, "C"=2}, 
{"A"=1, "B"=11, "C"=2}

代码

    ArrayList mylist = new ArrayList();

    Map<String,Integer> mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",1);
    mMap.put("C",3);
    mylist.add(mMap); 

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",1);
    mMap.put("C",2);
    mylist.add(mMap); 

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",11);
    mMap.put("C",2);
    mylist.add(mMap);

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",2);
    mMap.put("C",2);
    mylist.add(mMap);

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",1);
    mMap.put("C",11);       
    mylist.add(mMap);

3 个答案:

答案 0 :(得分:7)

像这样定义你自己的比较器:

public class MyMapComparator implements Comparator<Map <String, Integer>> 
{
    @Override
    public int compare (Map<String, Integer> o1, Map<String, Integer> o2) 
    {
        int c;

        c = o1.get ("A").compareTo(o2.get ("A"));
        if (c != 0) return c;

        c = o1.get ("B").compareTo(o2.get ("B"));
        if (c != 0) return c;

        return o1.get ("C").compareTo(o2.get ("C"));
    }
}

然后用它来对你的清单进行排序:

Collections.sort (mylist, new MyComparator ());

答案 1 :(得分:1)

您需要使用Collections.sort(list, comparator) Comparator<Map>实现您的自定义比较逻辑

答案 2 :(得分:1)

这是一个如何对编译和运行的HashMaps的ArrayList进行排序的例子 - 我找不到这样的例子 - 所以,除非我拙劣的剪切&amp;从我的戴尔迷你粘贴这很容易,这应该做到。

import java.util.*;
import java.lang.*;

public class test {

public static class mySort implements Comparator<HashMap<String,Integer>> {

    @Override
    public int compare(HashMap<String, Integer> map1, HashMap<String, Integer> map2) {
        return map1.get("number").intValue() - map2.get("number").intValue();
    }
}


static void displayAL(ArrayList<HashMap> al) {

    Iterator it = al.iterator();
    HashMap<String,Integer> hm;

    while (it.hasNext()) {

      hm = (HashMap<String,Integer>)it.next();
      System.out.println(hm.get("number"));

    }

    System.out.println();

}


public static void main(String[] args) {

    ArrayList<HashMap> al = new ArrayList<HashMap>();
HashMap<String,Integer> hm = new HashMap<String,Integer>();

hm.put("number",10);
al.add(hm);
hm = new HashMap<String,Integer>();
hm.put("number",2);
al.add(hm);
hm = new HashMap<String,Integer>();
hm.put("number",0);
al.add(hm);
hm = new HashMap<String,Integer>();
hm.put("number",-3);
al.add(hm);

displayAL(al);

Collections.sort((ArrayList)al,new mySort());

System.out.println("sorted:\n");

displayAL(al);

  }
}


rick@rick-jolicloud:~/javaProjects$ java test
10
2
0
-3

sorted:

-3
0
2
10