HashMap按key和按value排序
按key或value排序,都可以使用如下方式
按key或value排序区别在于重写Comparator方法;
下面的例子是按value进行排序:
-
将entrySet转换为List,然后重写比较器比较即可
-
需要排序的map:Map<String, SensorWarningLog> collect2,排好序后重新put到LinkedHashMap,这样就是排好序的map了
ArrayList<Map.Entry<String, SensorWarningLog>> entries = new ArrayList<>(collect2.entrySet());
entries.sort(new Comparator<Map.Entry<String, SensorWarningLog>>() {
@Override
public int compare(Map.Entry<String, SensorWarningLog> o1, Map.Entry<String, SensorWarningLog> o2) {
int i = o2.getValue().getId().compareTo(o1.getValue().getId());
return i;
}
});
LinkedHashMap<String, SensorWarningLog> map = new LinkedHashMap<>();
for (Map.Entry<String, SensorWarningLog> mapping : entries) {
map.put(mapping.getKey(),mapping.getValue());
}