标签:col 包装 integer package set stat eem eof span
测试内容:
TreeMap<Person,Integer> 的两级排序 1.先按Person.id 从小到大 (需要把int类型转换成包装类 Integer, 才可以使用p1.getId().compareTo( p2.getId())) 2.若id重复,则按然后再按Person.Name 从小到大排序(可以使用String类内置的 compareTo())
测试代码:
package 任务151;
import java.lang.*;
import java.util.*;
public class TestTreeMap {
public static void main(String[] args) {
Comparator comp=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; //先按Person.id 从小到大
if (p1.getId().compareTo( p2.getId()) ==0 ) //然后再按Name 从小到大排序
return p1.getName().compareTo(p2.getName());
else
return p1.getId().compareTo( p2.getId());
}
return 0;
}
};
Map<Person,Integer> mp=new TreeMap<>(comp);
mp.put(new Person("AA",22),788);
mp.put(new Person("BB",24),783);
mp.put(new Person("GG",42),718);
mp.put(new Person("DD",42),178);
Set st1=mp.keySet();
for(Object o:st1){
Person p=(Person)o;
System.out.println("["+p.name+","+p.id+"]"+": "+mp.get(o)); //构成键--值对
}
}
}
class Person{
String name;
Integer id;
public Person(String name, int id) {
this.name = name;
this.id = (Integer)id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
结果:
[AA,22]: 788 [BB,24]: 783 [DD,42]: 178 [GG,42]: 718
Java基础- TreeMap<Person,Integer> 实现的定制排序(Comparator 接口)
标签:col 包装 integer package set stat eem eof span
原文地址:https://www.cnblogs.com/zhazhaacmer/p/9792144.html