Java

如何结合Lambda表达式使用Java sorted()函数

小樊
85
2024-08-27 12:22:13
栏目: 编程语言

在Java中,可以通过使用sorted()函数与Lambda表达式结合对集合进行排序

首先,确保已经导入了以下所需的类:

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

接下来,创建一个简单的实体类,例如Person

public class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

现在,创建一个Person对象的列表并使用sorted()函数对其进行排序。这里我们将使用两种不同的排序方法:按姓名排序和按年龄排序。

public class Main {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // 按姓名排序(升序)
        List<Person> sortedByName = people.stream()
                .sorted((p1, p2) -> p1.getName().compareTo(p2.getName()))
                .collect(Collectors.toList());
        System.out.println("Sorted by name: " + sortedByName);

        // 按年龄排序(升序)
        List<Person> sortedByAge = people.stream()
                .sorted((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
                .collect(Collectors.toList());
        System.out.println("Sorted by age: " + sortedByAge);
    }
}

运行上述代码,你将看到如下输出:

Sorted by name: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]
Sorted by age: [Person{name='Bob', age=25}, Person{name='Alice', age=30}, Person{name='Charlie', age=35}]

在这个示例中,我们使用了Lambda表达式作为sorted()函数的参数,以便根据需要对Person对象列表进行排序。

0
看了该问题的人还看了