java stream-终结操作 count、max、min 作者:马育民 • 2023-04-07 22:50 • 阅读:10207 # count 返回流中数据的数量 ``` List list = new ArrayList<>(); Collections.addAll(list,"李雷", "韩梅梅", "lucy", "lisi","李小四"); long count = list.stream() .filter(item -> item.startsWith("李")) // 过滤姓李的数据 .count(); System.out.println("总共元素:"+count); ``` # max 获取最大值 ### 元素是数字类型 ``` List list = new ArrayList<>(); Collections.addAll(list,1,2,3,4); Optional res = list.stream() .min(Integer::compare); // 指定比较方式 System.out.println(res.get()); ``` ### 元素是对象类型 如果 `List` 中的元素是类对象,处理起来要稍微复杂些 `Student` 类: ``` package std; public class Student{ String name; int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ``` 核心代码: ``` List list = new ArrayList<>(); Collections.addAll(list, new Student("李雷",20), new Student("韩梅梅",19), new Student("lili",24), new Student("lucy",22) ); Optional res = list.stream() .max(Comparator.comparingInt(Student::getAge)); // 指定比较 age System.out.println(res.get()); ``` **提示:** `Comparator.comparingInt` 的底层代码如下: [![](/upload/0/0/1IX5KsJxdc74.png)](/upload/0/0/1IX5KsJxdc74.png) 可知底层调用的是:`Integer.compare()` 方法 # min 获取最小值 ``` List list = new ArrayList<>(); Collections.addAll(list,1,2,3,4); Optional res = list.stream() .max(Integer::compare); System.out.println(res.get()); ``` 原文出处:http://malaoshi.top/show_1IX5HCciJkT3.html