java8 新特性Lambda表达式之TreeSet

//综合案例:集合TreeSet==>自带排序的集合

public class Event_TreeSet {

public static void main(String[] ags) {

//TreeSet中有一个方法:public TreeSet(Comparator comparator) {this(new TreeMap<>(comparator));},

    //但是这个方法需要一个Comparator作为参数,而这个参数Comparator又是一个函数式接口,int compare(T o1, T o2); so 你懂得!

//第一种:

//Set personSet=new TreeSet<>((ele1,ele2)-> ele1.getAge()-ele2.getAge());

//第二种:这两种只是不同的实现方式而已

Set personSet=new TreeSet<>((ele1,ele2)->{

if(ele1.getAge()>ele2.getAge()) {

return 1;

}else {

return -1;

}

});

personSet.add(new Person("Lily",10));

personSet.add(new Person("Poliy",20));

personSet.add(new Person("LiHui",15));

personSet.add(new Person("Lucy",13));

//直接打印的话:抛异常:Person cannot be cast to java.lang.Comparable

//多个person进行对比 不知道哪个person大 哪个小 无法直接对比

System.out.println(personSet);

//输出:

//[Person [name=Lily, age=10], Person [name=Lucy, age=13], Person [name=LiHui, age=15], Person [name=Poliy, age=20]]

    }

}

你可能感兴趣的:(java8,新特性Lambda表达式)