public class Main {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap<>();
TreeMap treeMap1 = new TreeMap<>();
treeMap.put(7, "h");
treeMap.put(8, "g");
treeMap.put(9, "f");
treeMap.put(10, "e");
treeMap.put(14, "a");
treeMap.put(1, "w");
treeMap.put(2, "v");
treeMap.put(3, "u");
treeMap.put(11, "d");
treeMap.put(12, "c");
treeMap.put(13, "b");
treeMap.put(4, "k");
treeMap.put(5, "j");
treeMap.put(6, "i");
System.out.println("----------------------*------------------------------");
while (treeMap.size() != 0) {
//treemap自动按照key进行递增排序
System.out.println(treeMap.firstEntry().getKey() + " - " + treeMap.firstEntry().getValue());
treeMap1.put(treeMap.firstEntry().getValue(), treeMap.firstEntry().getKey());
treeMap.remove(treeMap.firstKey());
}
System.out.println("----------------------*------------------------------");
while (treeMap1.size() != 0) {
//treemap自动按照key进行递增排序
System.out.println(treeMap1.firstEntry().getKey() + " - " + treeMap1.firstEntry().getValue());
treeMap1.remove(treeMap1.firstKey());
}
System.out.println("----------------------*------------------------------");
}
}
得到结果:
----------------------*------------------------------
1 - w
2 - v
3 - u
4 - k
5 - j
6 - i
7 - h
8 - g
9 - f
10 - e
11 - d
12 - c
13 - b
14 - a
----------------------*------------------------------
a - 14
b - 13
c - 12
d - 11
e - 10
f - 9
g - 8
h - 7
i - 6
j - 5
k - 4
u - 3
v - 2
w - 1
----------------------*------------------------------
2.按照value排序
public class Main {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap<>();
treeMap.put("s", 2);
treeMap.put("w", 5);
treeMap.put("d", 1);
treeMap.put("f", 0);
treeMap.put("h", 9);
treeMap.put("q", 22);
treeMap.put("a", 25);
//按照value排序
List
结果:
----------------------*------------------------------
f - 0
d - 1
s - 2
w - 5
h - 9
q - 22
a - 25
----------------------*------------------------------
注意:
List<Map.Entry<String, Integer>> entryArrayList = new ArrayList<>(treeMap.entrySet());
Collections.sort(entryArrayList, Comparator.comparing(Map.Entry::getValue));
等价于下面的lamda:
List> entryArrayList = new ArrayList<>(treeMap.entrySet());
Collections.sort(entryArrayList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
也等价于:
List<Map.Entry<String, Integer>> entryArrayList = new ArrayList<>(treeMap.entrySet());
Collections.sort(entryArrayList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});