测试类
public class LambdaMethod {
@Test
public void test1() {
Comparator<Person> com1 = (o1, o2) -> {
int age = Integer.compare(o1.getAge(), o2.getAge());
if (age > 0) {
return -1;
} else if (age < 0) {
return 1;
} else {
return -o1.getName().compareTo(o2.getName());
}
};
Set<Person> set = new TreeSet<>(com1);
set.add(new Person("Tom", 12));
set.add(new Person("Lisa", 6));
set.add(new Person("Mac", 20));
set.add(new Person("Bili", 6));
System.out.println(set);
@Test
public void test1() {
Set<Person> set = new TreeSet<>((o1, o2) -> {
int age = Integer.compare(o1.getAge(), o2.getAge());
if (age > 0) {
return -1;
} else if (age < 0) {
return 1;
} else {
return -o1.getName().compareTo(o2.getName());
}
});
set.add(new Person("Tom", 12));
set.add(new Person("Lisa", 6));
set.add(new Person("Mac", 20));
set.add(new Person("Bili", 6));
System.out.println(set);
}
}
@Test
public void test2() {
Set<Person> set = new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
int age = Integer.compare(p1.getAge(),p2.getAge());
if(age > 0) {
return -1;
} else if(age < 0) {
return 1;
} else {
return -p1.getName().compareTo(p2.getName());
}
}
});
set.add(new Person("Tom", 12));
set.add(new Person("Lisa", 6));
set.add(new Person("Mac", 20));
set.add(new Person("Bili", 6));
System.out.println(set);
}
}
Person类
public class Person {
protected int age;
protected String name;
public Person( String name, int age) {
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}