MST

星途 面试题库

面试题:Java中如何使用Stream sorted方法按对象的某个属性自定义排序

假设有一个Java类Student,包含属性name(String类型)和age(int类型)。请使用Java Stream的sorted方法,按学生的age属性升序对Student对象的集合进行排序,并返回排序后的结果。
37.6万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

假设Student类有相应的getter方法,以下是示例代码:

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

class Student {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("Alice", 20));
        studentList.add(new Student("Bob", 18));
        studentList.add(new Student("Charlie", 22));

        List<Student> sortedList = studentList.stream()
               .sorted(Comparator.comparingInt(Student::getAge))
               .collect(Collectors.toList());

        sortedList.forEach(student -> System.out.println("Name: " + student.getName() + ", Age: " + student.getAge()));
    }
}

在上述代码中:

  1. 定义了Student类,包含nameage属性及相应的getter方法。
  2. main方法中创建了Student对象的列表。
  3. 使用stream()方法将列表转换为流,通过sorted(Comparator.comparingInt(Student::getAge))age属性升序排序,最后使用collect(Collectors.toList())将流转换回列表。
  4. 遍历打印排序后的列表。