1:TreeMap包含去重,排序功能。
对于去重功能,它默认对基本数据类型进行值的覆盖。就是如果两个键值对的键一样,值不同,那么后添加的键值对会覆盖之前的键值对。一旦涉及到自定义的数据类型即类,我们要在可以在TreeMap里重新写 Comparator,compare方法里返回0就是代表两个键相同,会去重,就是使用第一个键值对的键使用第二个键的值。可以不用重写equals和hashcode方法,这一点和TreeSet的去重机制一样。对于排序功能,默认是升序和按字典序排列。对于我们自定义排序,可以在类中继承Comparable<>重写compareTo方法,对于大于int类型的整数比较可以在重写的也可以在compareTo方法中写上Long.compare()。第二种方法直接在
TreeMap<Integer,Integer> tm2=new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Long.compare(o1,o2); } });这样写。
TreeMap的添加与遍历方式同HashMap,在这里不在重述。
2:文章主要内容四个方法
1:TreeMap
import java.util.*;
public class Main3 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
TreeMap<Integer,Integer> tm=new TreeMap<>();
tm.put(0,90);
tm.put(1,2);
tm.put(2,3);
tm.put(4,76);
tm.put(6,1);
Map.Entry<Integer, Integer> integerIntegerEntry = tm.ceilingEntry(3);
System.out.println(integerIntegerEntry.getKey()+" "+integerIntegerEntry.getValue());
Map.Entry<Integer,Integer> in=tm.floorEntry(3);
System.out.println(in.getKey()+" "+in.getValue());
int cc=tm.ceilingKey(3);
System.out.println(cc+" "+tm.get(cc));
int dd=tm.floorKey(3);
System.out.println(dd+" "+tm.get(dd));
}
}
第一个知识点:键值对。
我们使用 Map.Entry<Integer, Integer> integerIntegerEntry来接受键值对
integerIntegerEntry可以替换成其他字母
第二个知识点: tm.ceilingEntry(),此方法返回第一个大于等于我们指定的键的键 值对
使用配套的getKey()和getValue()可以获得键值对里的键和元素值
第三个知识点: tm.floorEntry(),此方法返回小于等于我们指定的键中最大的键值 对。
得到这个键值对的键和元素同第二个知识点
第四个知识点: ceilingKey()这东西是返回大于等于我们指定的键的最小键
floorKey()是返回小于等于我们指定键的最大键
代码运行截图
附上自定义类型的去重
import java.util.*; import java.io.*; public class Main3 { //利用treemap的ceilingEntry和floorEntry public static void main(String[] args) { TreeMap<aaa,Integer> tm=new TreeMap<>(new Comparator<aaa>() { @Override public int compare(aaa o1, aaa o2) { return o1.a-o2.a; } }); aaa a1=new aaa(1,2); aaa a2=new aaa(1,3); tm.put(a1,1); tm.put(a2,3); System.out.println(tm); } } class aaa{ int a; int b; public aaa(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "aaa{" + "a=" + a + ", b=" + b + '}'; } }
运行截图
分析:我们比较器里按照a的大小进行排序,对象a1与a2的a一样大,虽然b不一样,但我们在书写比较器原则时认为a一样,这两个对象就一样,所以键值对里的键保留了第一个,而值更新了