为什么age为2的对象会排在age为-1对象的前面
比较类:
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
if (o1.name.equals("lili") || o2.name.equals("lili")) {
return o1.age - o2.age;
} else {
return o1.id - o2.id;
}
}
}客户端:
public static void main(String[] args) throws IOException {
Person person = new Person("lili", 3, null, 1);
Person person1 = new Person("aa", 2, null, 2);
Person person3 = new Person("lili", -1, null, 3);
Person person2 = new Person("bb", -9, null, 4);
Person person4 = new Person("bb1", 5, null, -5);
List<Person> collect = Stream.of(person2, person1, person, person3,person4).collect(Collectors.toList());
List<Person> collect1 = collect.stream().sorted(new PersonComparator()).collect(Collectors.toList());
collect1.forEach(System.out::println);
}比较结果:
Person{name='aa', age=2, id=2, pet=null}
Person{name='bb', age=-9, id=4, pet=null}
Person{name='lili', age=-1, id=3, pet=null}
Person{name='lili', age=3, id=1, pet=null}
Person{name='bb1', age=5, id=-5, pet=null}无