如何对哈希映射的矢量进行排序

时间:2011-10-20 17:37:18

标签: java sorting vector hashmap

我有一个Hashmap矢量,HashMap包含不同的数据类型:

Vector<HashMap<String, Object>> theVector= new Vector<HashMap<String, Object>>();

theResults包含这个HashMap:

HashMap<String, Object> theHashMap= new HashMap<String, Object>();

theHashMap包含以下数据: (假装这是一个for循环)

//1st set

theHashMap.put("BLDG_ID", 111); //int
theHashMap.put("EMP_NAME", "AAA"); //String
theHashMap.put("FLAG", true); //boolean

theVector.add(theHashMap);

//2nd set

theHashMap.put("BLDG_ID", 222); //int
theHashMap.put("EMP_NAME", "BBB"); //String
theHashMap.put("FLAG", false); //boolean

theVector.add(theHashMap);

//2nd set<br>
theHashMap.put("BLDG_ID", 111); //int
theHashMap.put("EMP_NAME", "CCC"); //String
theHashMap.put("FLAG", false); //boolean

theVector.add(theHashMap);

我想根据BLDG_ID对HashMap矢量的内容进行排序,这样当我显示数据时,它看起来就像是

BLDG_ID || EMP_NAME
111     ||    AAA
111     ||    CCC
222     ||    BBB

我该怎么做?

3 个答案:

答案 0 :(得分:2)

我认为你做这样的事情要好得多:不要为你的值使用hashmap,只需要创建一个类。然后,您将获得compile time checking操作,这将有助于防止错误发生。

class Employee implements Comparable<Employee> {
    int buildingId;
    String name;
    boolean flag;

    Employee(int b, String n, boolean f) {
        buildingId = b;
        name = n;
        flag = f;
    }

    public int compareTo(Employee other) {
        if(other.buildingId == this.buildingId) 
            return name.compareTo(other.name);
        return buildingId - other.buildingId; // potential for overflow, be careful
    }

}

然后你可以使用你想要的任何种类对矢量进行排序。如果使用ArrayList(Vector的现代形式),则可以使用Collections.sort(myList);

List<Employee> emps = new ArrayList<Employee>();
emps.add(new Employee(111,"AAA",true));
emps.add(new Employee(111,"CCC",false));
emps.add(new Employee(111,"BBB",false));

Collections.sort(emps);
System.out.println("Building Id,Employee Name");
for(Employee emp : emps) System.out.println(emp.getCSV()); // or however you want to format it

答案 1 :(得分:1)

实施自定义Comparator<Map<String, Object>>,然后调用Collections.sort

注意:您可能希望使用ArrayList而不是Vector。

答案 2 :(得分:1)

List<Map<String, Object>> vector = new Vector<Map<String, Object>>();

Collections.sort(vector, new Comparator<Map<String, Object>>() {
    @Override
    public int compare(Map<String, Object> map1, Map<String, Object> map2) {
        return ((Integer) map1.get("BLDG_ID")).compareTo((Integer) map2.get("BLDG_ID")));
    }            
});

更新:代码:

在“最后”之后

theVector.add(theHashMap);

添加以下内容

Collections.sort(theVector, new Comparator<HashMap<String, Object>>() {
        @Override
        public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
            return ((Integer) o1.get("BLDG_ID")).compareTo((Integer) o2.get("BLDG_ID"));
        }            
    });