• 欢迎光临~

# .sorted关键字进行比较排序

``````package q;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;
import java.util.stream.Collectors;

public class StreamTest {
public static void main(String[] args) {
Person person1 = new Person();
person1.setAge(21);
person1.setName("21");

Person person2 = new Person();
person2.setAge(19);
person2.setName("19");

Person person3 = new Person();
person3.setAge(19);
person3.setName("20");

Person person4 = new Person();
person4.setAge(20);
person4.setName("20");

Person person5 = new Person();
person5.setAge(19);
person5.setName("18");

List<Person> people = new ArrayList<>();

List<Person> collect1 = people.stream().sorted((Comparator.comparing(Person::getAge))).collect(Collectors.toList());//只根据年龄排序，升序
System.out.println(collect1);

List<Person> collect2 = people.stream().sorted((Comparator.comparing(Person::getAge)).reversed()).collect(Collectors.toList());//只根据年龄排序，降序
System.out.println(collect2);

List<Person> collect3 = people.stream().sorted((Comparator.comparing(Person::getAge)).thenComparing(Comparator.comparing(Person::getName))).collect(Collectors.toList());//先根据年龄进行排序，遇见相同的，然后根据姓名进行排序，都升序
System.out.println(collect3);

List<Person> collect4 = people.stream().sorted((Comparator.comparing(Person::getAge)).thenComparing(Comparator.comparing(Person::getName)).reversed()).collect(Collectors.toList());//先根据年龄进行排序，遇见相同的，然后根据姓名进行排序，降序【都降序】
System.out.println(collect4);

List<Person> collect5 = people.stream().sorted(Comparator.comparing(Person::getAge).reversed().thenComparing(Comparator.comparing(Person::getName)).reversed()).collect(Collectors.toList());//年龄升序，姓名降序
System.out.println(collect5);

List<Person> collect6 = people.stream().sorted(Comparator.comparing(Person::getAge).reversed().thenComparing(Comparator.comparing(Person::getName))).collect(Collectors.toList());//根据年龄降序，姓名升序
System.out.println(collect6);
}
}

@Data
@NoArgsConstructor
@ToString
class Person {
private String name;
private Integer age;
}
``````