Java 8 Stream流对对象的排序(一个对象里面的多个属性进行排序)

1.要对一个对象里面的多个字段进行排序

可以这么写,假设
List list = new ArrayList<>();
这个类有多个属性,先根据年龄再根据身高排序
@Data
public class People {
    private int age;
    private int height;
}

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

/**
 * Created by FangPing on 2020-04-01
 */
public class Test {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        People people = new People();
        people.setAge(1);
        people.setHeight(2);
        list.add(people);
        People people1 = new People();
        people1.setAge(2);
        people1.setHeight(1);
        list.add(people1);
        Comparator comparator = (o1, o2) -> {
            int ageA = o1.getAge();
            int ageB = o2.getAge();
            if (ageA != ageB) {
                return ageA - ageB;
            }

            int heightA = o1.getHeight();
            int heightB = o2.getHeight();
            if (heightA != heightB) {
                return heightA - heightB;
            }
            return 0;
        };
        // 最终的结果
        list = list.stream().sorted(comparator).collect(Collectors.toList());
        for (int i=0;i

 

 

你可能感兴趣的:(java)