我有一个 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/