package CollectionTest;
import java.util.TreeSet;
import java.util.Comparator;
class M
{
int age;
public M(int age)
{
this.age = age;
}
public String toString()
{
return "M[age:" + age + "]";
}
}
public class TreeSetDemo
{
public static void main(String[] args)
{
MDemo1();
MDemo2();
MDemo3();
}
public static void MDemo1(){
//使用Lambda
// 此处Lambda表达式的目标类型是Comparator
TreeSet<M> ts = new TreeSet<M>((o1 , o2) ->
{
M m1 = (M)o1;
M m2 = (M)o2;
// 根据M对象的age属性来决定大小,age越大,M对象反而越小
return m1.age > m2.age ? -1
: m1.age < m2.age ? 1 : 0;
});
ts.add(new M(5));
ts.add(new M(-3));
ts.add(new M(9));
System.out.println(ts);
}
public static void MDemo2(){
//使用比较类,不用变更M类,而是建立比较类,作为参数传递给TreeSet
TreeSet<M> ts = new TreeSet<M>(new MComparator());
ts.add(new M(5));
ts.add(new M(-3));
ts.add(new M(9));
System.out.println(ts);
}
public static void MDemo3(){
//使用比较类,不用变更M类,而是建立比较类,作为参数传递给TreeSet
TreeSet<M2> ts = new TreeSet<M2>();
ts.add(new M2(5));
ts.add(new M2(-3));
ts.add(new M2(9));
System.out.println(ts);
}
}
class MComparator implements Comparator<M>{
@Override
public int compare(M o1, M o2) {
return o1.age-o2.age;
}
}
//若使用compareTo方法就要改变M类
class M2 implements Comparable<M2>
{
int age;
public M2(int age)
{
this.age = age;
}
public String toString()
{
return "M2[age:" + age + "]";
}
@Override
public int compareTo(M2 o) {
// TODO Auto-generated method stub
return this.age-o.age;
}
}
Java中TreeSet使用Lambda和比较类的方法
最新推荐文章于 2023-03-05 21:45:02 发布