1. 原始类
/**
* 将对象作为TreeMap的key,此时需要给对象类需要具备比较功能、需要实现Comparable接口
* @author bruce
* 此类对象主要是用要用于TreeMap的key
*/
public class Student implements Comparable<Student> {
private int age;
private String name;
public Student(String name, int age) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 先按age比较,如果age相等比较name
*/
@Override
public int compareTo(Student o) {
int res = this.age - o.age;
return res == 0 ? this.name.compareTo(o.name) : res ;
}
}
2. 自定义比较器
import java.util.Comparator;
public class MyComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
int res = o1.getName().compareTo(o2.getName());
return res == 0 ? o1.getAge() - o2.getAge() : res;
}
}
3. demo
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import org.junit.Test;
/**
* 将对象作为TreeMap的key,此时需要给对象类需要具备比较功能、需要实现Comparable接口
* @author bruce
*
*/
public class TreeMapDemo {
/**
* 按照Student中定义的默认比较方法<先比较年龄,如果年龄相等比较姓名>进行比较
*/
// @Test
public void defaultComparable(){
TreeMap<Student, String> map = new TreeMap<Student, String>();
map.put(new Student("xiaosan", 23), "上海");
map.put(new Student("xiaosi", 27), "北京");
map.put(new Student("xiaosan", 25), "上海");
map.put(new Student("xiaowu", 26), "深圳");
Set<Student> set = map.keySet();
Iterator<Student> iterator = set.iterator();
while(iterator.hasNext()){
Student student= iterator.next();
System.out.println(" key = " + student + " value = " + map.get(student));
}
}
/**
* 使用比较器,先比较姓名、如果姓名相等比较年龄
*/
@Test
public void createComparable(){
TreeMap<Student, String> map = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//先按照姓名比较
int res = o1.getName().compareTo(o2.getName());
return res == 0 ? o1.getAge() - o2.getAge() : res;
}
});
map.put(new Student("5", 26), "上海");
map.put(new Student("1", 26), "北京");
map.put(new Student("3", 26), "上海");
map.put(new Student("4", 26), "深圳");
Iterator<Student> iterator = map.keySet().iterator();
while(iterator.hasNext()){
Student student = iterator.next();
System.out.println(" key = " + student + " value = " + map.get(student));
}
}
}