package com.atguigu.java;
import org.junit.Test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
/**
* @author Dxkstart
* @create 2021-05-23 18:29
*/
public class TreeMapTest {
//向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
//因为要按照key进行排序:自然排序 、 定制排序
//自然排序
@Test
public void test1(){
TreeMap map = new TreeMap();
Person p1 = new Person("Tom", 12);
Person p2 = new Person("Jerry", 19);
Person p3 = new Person("Jack", 20);
Person p4 = new Person("Rose", 18);
map.put(p1,89);
map.put(p2,79);
map.put(p3,90);
map.put(p4,98);
//遍历
Set set = map.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
//定制排序 --->按年龄排序
@Test
public void test2(){
TreeMap map = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Person && o2 instanceof Person){
Person p1 =(Person)o1;
Person p2 =(Person)o2;
return Integer.compare(p1.getAge(),p2.getAge());
}
throw new RuntimeException("输入的类型不匹配!");
}
});
Person p1 = new Person("Tom", 12);
Person p2 = new Person("Jerry", 19);
Person p3 = new Person("Jack", 20);
Person p4 = new Person("Rose", 18);
map.put(p1,89);
map.put(p2,79);
map.put(p3,90);
map.put(p4,98);
//遍历
Set set = map.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}