java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java stream多字段排序

Java的stream流多个字段排序的实现

作者:码奴生来只知道前进~

本文主要介绍了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<Person> people = Arrays.asList(
                new Person("张三", 30, 5000),
                new Person("李四", 25, 6000),
                new Person("王五", 35, 4000)
        );

        List<Person> 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<Person> people = Arrays.asList(
                new Person("张三", 30, 5000),
                new Person("李四", 25, 6000),
                new Person("王五", 35, 4000)
        );

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

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

        System.out.println(sortedPeople);
    }

    private static Comparator<Person> 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的stream流多个字段排序的实现的文章就介绍到这了,更多相关Java stream多字段排序内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文