Map集合按照Key键的升序与降序
Map<String, String> map = new TreeMap<>();
Map<String, String> map = new TreeMap<>((o1, o2) -> o1.compareTo(o2));
Map<String, String> map = new TreeMap<>(Collections.reverseOrder());
Map<String, String> map2 = new TreeMap<String, String>((o1, o2) -> o2.compareTo(o1));
Map<String, String> map1 = new TreeMap<String, String>(new Comparator<String>() {
public int compare(String k1, String k2) {
return k2.compareTo(k1);
}
});
Map集合按照Value键的升序与降序
- 暂时想到的两种解决方案(新起Map存放、或者新起list存放)(若有更好的解决方案再回来添加)
- 升序
Map<String, String> map = new TreeMap();
Map<String, String> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
Map<String, String> map = new TreeMap();
list.sort((Map.Entry<String, String> entry1,Map.Entry<String, String> entry2)->entry1.getValue().compareTo(entry2.getValue()));
List<Map.Entry<String, String>> list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> entry1, Map.Entry<String, String> entry2) {
return entry2.getValue().compareTo(entry1.getValue());
}
});