TreeMap
-
TreeMap在SortedMap接口下.
-
TreeSet底层也是调用的TreeMap
-
用法和TreeSet一样,不过变成键值对
-
可以用定制比较器
package com.li.changGe.maps;
import com.li.changGe.pojo.Student;
import java.util.*;
/**
* TreeMap在SortedMap接口下.
* TreeSet底层也是调用的TreeMap
*
* 用法和TreeSet一样,不过变成键值对
*/
public class TreeMapDemo01 {
public static void main(String[] args) {
//定制比较器
TreeMap<Student,String> treeMap = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
});
Student student = new Student("长歌",18,'女');
Student student1 = new Student("世民",22,'男');
Student student2 = new Student("则天",20,'女');
treeMap.put(student,"燕京");
treeMap.put(student1,"长安");
treeMap.put(student2,"静安");
//-------------------------------------------------
/**
* 也是重复后覆盖
* 最好不要用null做键,因为要调用compareTo方法比较
* 会NullPointException
*/
treeMap.put(new Student("长歌",18,'女'),"北凉");
//treeMap.put(null,null);
Set<Map.Entry<Student, String>> entries = treeMap.entrySet();
//-------------------------------------------------
/**
* Student{name='世民', age=22, sex=男}
* -长安
* Student{name='则天', age=20, sex=女}
* -静安
* Student{name='长歌', age=18, sex=女}
* -北凉
*/
Iterator<Map.Entry<Student, String>> iterator1 = entries.iterator();
while (iterator1.hasNext()){
Map.Entry<Student, String> next = iterator1.next();
System.out.println(next.getKey()+"-"+next.getValue());
}
}
}