我有一个HashMap,其中字符串为键,对象为值。如何通过Objects中的FirstName字段对HashMap进行排序。这是实际的HashMap表示HashMap<String, AttendanceData> attendanceDataMap=new HashMap<String, AttendanceData>();
HashMap的键将是AttendanceData Object的id
AttendanceData类看起来像
public class AttendanceData{
private TakenBy takenBy;
private String id;
private String user_name;
private String first_name;
private String description;
private String last_name;
public AttendanceData(String id, String firstName, String lastName, String takenBy, String description, String userName)
{
this.id=id;
this.first_name=firstName;
this.last_name=lastName;
this.takenBy=takenBy;
this.description=description;
this.user_name=userName;
}
答案 0 :(得分:1)
我认为比较者可能会有所帮助,粘贴下面的示例,请注意这不是具体的答案,您必须根据您的需要进行修改:
public class HMapSortingByvalues {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(5, "A");
hmap.put(11, "C");
hmap.put(4, "Z");
hmap.put(77, "Y");
hmap.put(9, "P");
hmap.put(66, "Q");
hmap.put(0, "R");
System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = sortByValues(hmap);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
private static HashMap sortByValues(HashMap map) {
List list = new LinkedList(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
// Here I am copying the sorted list in HashMap
// using LinkedHashMap to preserve the insertion order
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
}
答案 1 :(得分:0)
HashMap不支持排序。但是,当然,您可以对值进行排序。实施可比较的例如:
List list = new ArrayList(Map.entrySet());
Collections.sort(list, new Comparator() {
@Override
public int compare(Entry e1, Entry e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
此外,您可以使用SortedMap(例如TreeMap)。但它只支持按键排序。虽然您可以尝试使用此比较器:
class ValueComparator implements Comparator {
Map base;
public ValueComparator(Map base) {
this.base = base;
}
public int compare(Object a, Object b) {
if((Double)base.get(a) < (Double)base.get(b)) {
return 1;
} else if((Double)base.get(a) == (Double)base.get(b)) {
return 0;
} else {
return -1;
}
}
}
答案 2 :(得分:-1)
List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.