This question already has answers here:
Sorting hashmap based on keys
(9个答案)
9个月前关闭。
如何排序哈希图包含数组列表作为键的值?并且还对arraylist进行排序?
...
...
现在,我想基于键进行排序。
并且还需要根据ID对每个键的ArrayList进行排序。
请注意,最好声明列表并将变量映射到接口,而不是实现,即
或者,考虑将
(9个答案)
9个月前关闭。
如何排序哈希图包含数组列表作为键的值?并且还对arraylist进行排序?
Hashmap<String, ArrayList<Events>> h = new HashMap<>();
ArrayList<Events> a = new ArrayList<>();
a.add(new Events("1", "name1", "Address1"));
a.add(new Events("2", "name2", "Address2"));
h.put("10-12-2014", a);
h.put("08-11-2014", a1);
...
...
现在,我想基于键进行排序。
并且还需要根据ID对每个键的ArrayList进行排序。
最佳答案
使用TreeMap
代替HashMap
,它会根据密钥的自然顺序自动排序。
要对ArrayList
进行排序,请使用静态Collections#sort(List, Comparator)
方法,并指定一个比较器对列表中的Events
对象进行排序。例如,假设您要按Events
构造函数的第一个参数称为id
进行排序,则可以按以下方式调用sort
:
Map<String, List<Events>> h = new HashMap<>();
List<Events> a = new ArrayList<>();
a.add(new Events("1", "name1", "Address1"));
a.add(new Events("2", "name2", "Address2"));
Collections.sort(a, new Comparator<Events>() {
@Override
public int compare(Events o1, Events o2) {
return o1.getId().compareTo(o2.getId());
}
});
h.put("10-12-2014", a);
... // similarly for list a1
Collections.sort(a1, new Comparator<Events>() {
@Override
public int compare(Events o1, Events o2) {
return o1.getId().compareTo(o2.getId());
}
});
h.put("08-11-2014", a1);
请注意,最好声明列表并将变量映射到接口,而不是实现,即
h
声明为Map
类型而不是HashMap
和a
为List
类型。或者,考虑将
Events
元素放在TreeSet
而不是ArrayList
中,并让Events
类实现Comparable
接口:class Events implements Comparable<Events> {
private String id;
...
@Override
public int compareTo(Events o) {
return this.getId().compareTo(o.getId());
}
}