Java的stream流多个字段排序

1、第一种是固定多个字段排序 

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

class Person {
    String name;
    int age;
    double salary;

    public Person(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

public class Main {
    public static void main(String[] args) {
        List people = Arrays.asList(
                new Person("张三", 30, 5000),
                new Person("李四", 25, 6000),
                new Person("王五", 35, 4000)
        );

        List sortedPeople = people.stream()
                .sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge).thenComparing(Person::getSalary))
                .collect(Collectors.toList());

        sortedPeople.forEach(System.out::println);
    }
}

2、第二种动态字段进行排序 

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

class Person {
    String name;
    int age;
    double salary;

    public Person(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

public class Main {
    public static void main(String[] args) {
        List people = Arrays.asList(
                new Person("张三", 30, 5000),
                new Person("李四", 25, 6000),
                new Person("王五", 35, 4000)
        );

        // 动态传入排序字段
        String sortField = "age"; // 可以修改为"name"或"salary"

        List sortedPeople = people.stream()
                .sorted(getComparator(sortField))
                .collect(Collectors.toList());

        System.out.println(sortedPeople);
    }

    private static Comparator getComparator(String sortField) {
        switch (sortField) {
            case "name":
                return Comparator.comparing(Person::getName);
            case "age":
                return Comparator.comparingInt(Person::getAge);
            case "salary":
                return Comparator.comparingDouble(Person::getSalary);
            default:
                throw new IllegalArgumentException("Invalid sort field: " + sortField);
        }
    }
}

你可能感兴趣的:(Java,java,开发语言)