Treemap按key和value降序排序

2023-05-12,,

Treemap是一种根据键排序的数据结构,可以通过重载它的比较器来按照值排序。要按键排序,可以使用默认的比较器,而要按值排序,可以创建一个自定义的比较器并将其传递给treemap的构造函数。

以下是按键和值分别排序的示例代码:

按键排序:

import java.util.*;

public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>(); // Add elements to the map
map.put(10, "John");
map.put(20, "Steve");
map.put(5, "Mary");
map.put(30, "Martin");
map.put(8, "David"); // Sort by key
TreeMap<Integer, String> sortedByKey = new TreeMap<Integer, String>(map);
System.out.println("Sorted Map by Key: " + sortedByKey); }
}

输出结果:

Sorted Map by Key: {5=Mary, 8=David, 10=John, 20=Steve, 30=Martin}

Treemap是一种基于红黑树实现的有序映射,因此它默认按照键的自然顺序进行排序。如果你需要按照键的降序排序,可以使用Java中的Comparator接口来实现。

以下是一个示例代码,演示了如何创建一个按照键的降序排列的TreeMap:

import java.util.Comparator;
import java.util.TreeMap; public class Main {
public static void main(String[] args) {
// 创建一个按键降序排列的TreeMap
TreeMap<String, Integer> map = new TreeMap<>(Comparator.reverseOrder()); // 添加键值对
map.put("c", 3);
map.put("a", 1);
map.put("d", 4);
map.put("b", 2); // 输出结果
System.out.println(map); // {d=4, c=3, b=2, a=1}
}
}

在这个例子中,我们使用了Comparator.reverseOrder()方法创建了一个比较器,它会将键按照自然顺序的逆序进行排序。然后我们将这个比较器传递给了TreeMap的构造函数中,这样就创建了一个按照键的降序排列的TreeMap。

当然,你也可以根据具体的需求,自定义比较器实现不同的排序方式。

按值排序:

import java.util.*;

public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>(); // Add elements to the map
map.put(10, "John");
map.put(20, "Steve");
map.put(5, "Mary");
map.put(30, "Martin");
map.put(8, "David"); // Sort by value
ValueComparator vc = new ValueComparator(map);
TreeMap<Integer, String> sortedByValue = new TreeMap<Integer, String>(vc);
sortedByValue.putAll(map);
System.out.println("Sorted Map by Value: " + sortedByValue);
}
} class ValueComparator implements Comparator<Integer> {
Map<Integer, String> map; public ValueComparator(Map<Integer, String> map) {
this.map = map;
} public int compare(Integer a, Integer b) {
if (map.get(a).compareTo(map.get(b)) > 0) {
return 1;
} else {
return -1;
}
}
}

输出结果:

Sorted Map by Value: {5=Mary, 8=David, 10=John, 20=Steve, 30=Martin}

请注意,当使用自定义的比较器来按值排序时,您需要将其传递给treemap的构造函数,而不是使用默认的构造函数。

Treemap按key和value降序排序的相关教程结束。

《Treemap按key和value降序排序.doc》

下载本文的Word格式文档,以方便收藏与打印。