面试题答案
一键面试假设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()));
}
}
在上述代码中:
- 定义了
Student
类,包含name
和age
属性及相应的getter方法。 - 在
main
方法中创建了Student
对象的列表。 - 使用
stream()
方法将列表转换为流,通过sorted(Comparator.comparingInt(Student::getAge))
按age
属性升序排序,最后使用collect(Collectors.toList())
将流转换回列表。 - 遍历打印排序后的列表。