java - 如何对 HashMap vector 进行排序

标签 java sorting vector hashmap

我有一个 Hashmap vector ,并且 HashMap 包含不同的数据类型:

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

theResults 包含此 HashMap:

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

HashMap 有这些数据: (假设这是一个 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 vector 的内容进行排序,以便当我显示数据时,它看起来像这样

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

我该怎么做?

最佳答案

我认为你最好做这样的事情:不要使用 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
    }

}

然后您可以使用您想要的任何排序对 vector 进行排序。如果您使用 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

关于java - 如何对 HashMap vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7839891/

相关文章:

python - 数据操作 - 当值为字母数字时排序索引

c - 获取数组中的最小值

c++ - 在两个坐标空间之间变换对象

c++ - C++高效完成多重转换

java - 使用 JPA(Hibernate 实现)和 MySQL 保证 FIFO

java - 如何克服 Scanner 中 armstrongnumber 计算中的错误匹配异常?

java中的javascript逗号运算符

java - VisualVM 探查器错误 : "Class JavaLaunchHelper is implemented in both ..bin/java and ..jre/lib"

java - 逻辑排序的比赛装置

c++ - 用单词和数字按字母顺序排列字符串