Java新特性玩转JDK8之流操作max和min函数
max函数
-
功能
- 根据条件找出集合中的最大值。
-
代码示例
- 返回学生对象集合中年龄最大的学生
public class Main {
public static void main(String[] args) {
List<Student> list = Arrays.asList(new Student(32),new Student(33),new Student(21),new Student(29),new Student(18));
// 拿到年龄最大的Student
Optional<Student> max = list.stream().max((obj1, obj2) -> Integer.compare(obj1.getAge(), obj2.getAge()));
// 打印 33
max.ifPresent(s -> System.out.println(s.getAge()));
}
}
min函数
-
功能
- 根据条件找出集合中的最小值。
-
代码示例
- 返回学生对象集合中年龄最小的学生。
public class Main {
public static void main(String[] args) {
List<Student> list = Arrays.asList(new Student(32),new Student(33),new Student(21),new Student(29),new Student(18));
// 拿到年龄最小的Student
Optional<Student> min = list.stream().min((obj1, obj2) -> Integer.compare(obj1.getAge(), obj2.getAge()));
// 打印 18
min.ifPresent(s -> System.out.println(s.getAge()));
}
}