Stream 流之 max、min

一、方法概述

max : 获取最大值

min : 获取最小值

Optional<T> max(Comparator<? super T> comparator)

max、min 方法参数类型为 Comparator 接口,利用比较器自定义排序

 

二、案例

public class StreamDemo {
    public static void main(String[] args) {
        List<Person> personList = Arrays.asList(
                new Person(1, "大毛", 30, 175),
                new Person(2, "二毛", 35, 170),
                new Person(3, "三毛", 26, 173),
                new Person(4, "小毛", 30, 175));

        // 获取 person 类型流
        Stream<Person> personStream = personList.stream();
        // 按照年龄升序排序,然后获取排序后的最大值 o1-o2 代表升序排序;o2-o1 代表降序排序
        Optional<Person> max = personStream.max(((o1, o2) -> o1.getAge() - o2.getAge()));
        System.out.println(max.get());
    }
}

  

 

posted @ 2022-07-19 10:33  变体精灵  阅读(5620)  评论(0)    收藏  举报