按 Key 升序
Comparator 实现
Map<Integer,Integer> sortMap = new TreeMap<Integer,Integer>(
new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
}
);
lambda 实现
LinkedHashMap sortMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
按 Key 降序
Comparator 实现
Map<Integer,Integer> sortMap = new TreeMap<Integer,Integer>(
new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
}
);
lambda 实现
LinkedHashMap sortMap = map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
按 Value 升序
Comparator 实现
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, Integer> sortMap = new LinkedHashMap<Integer, Integer>();
List<Map.Entry<Integer, Integer>> entryList = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<Integer, Integer>>(){
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o1.getValue()-o2.getValue();
}
});
for(Map.Entry<Integer, Integer> tmpEntry:entryList){
sortMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
lambda 实现
LinkedHashMap sortMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
按 Value 降序
Comparator 实现
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, Integer> sortMap = new LinkedHashMap<Integer, Integer>();
List<Map.Entry<Integer, Integer>> entryList = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<Integer, Integer>>(){
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o2.getValue()-o1.getValue();
}
});
for(Map.Entry<Integer, Integer> tmpEntry:entryList){
sortMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
lambda 实现
LinkedHashMap sortMap = map.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
自定义复杂排序
按照每个值的频率 升序 排序。如果有多个值的频率相同,按照数值本身将它们 降序 排序。
Map<Integer, Integer> map = new HashMap<>();
List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2) {
int val = o1.getValue().compareTo(o2.getValue());
if (val == 0) {
return o2.getKey() - o1.getKey();
}
return val;
}
});
for (Map.Entry<Integer, Integer> entry : list) {
}