import java.util.*; import java.util.stream.Collectors; // 流对象只能收集一次!!! public class StreamTest4 { public static void main(String[] args) { List<Student> students = new ArrayList<>(); Student student1 = new Student("蜘蛛精", 26, 172.5); Student student2 = new Student("蜘蛛精", 26, 172.5); Student student3 = new Student("紫霞仙子", 23, 167.6); Student student4 = new Student("白晶晶", 25, 169.0); Student student5 = new Student("牛魔王", 35, 183.3); Student student6 = new Student("牛夫人", 34, 168.5); Collections.addAll(students, student1, student2, student3, student4, student5, student6); // 计算身高超过168的学生有几人 long size = students.stream().filter(s -> s.getHeight() > 168).count(); System.out.println(size); // count用于统计元素个数 // 找出身高最高的学生对象,并输出 Student s = students.stream().max((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight())).get(); System.out.println(s); // max用于获取最大值 // get方法用于获取当前对象 // 找出身高最矮的学生对象, 并输出 Student ss = students.stream().min((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight())).get(); System.out.println(ss); // min方法用于获取最小值 // 找出身高超过170的学生对象, 并放到一个新集合中去返回 List<Student> students1 = students.stream().filter(a -> a.getHeight() > 170) .collect(Collectors.toList()); System.out.println(students1); Set<Student> students2 = students.stream().filter(a -> a.getHeight() > 170) .collect(Collectors.toSet()); System.out.println(students2); // collect方法将选取后的元素放入一个新的集合中去 // 找出身高超过170的学生对象, 并把学生对象的名字和身高, 存入一个 Map集合并返回 Map<String, Double> map = students.stream().filter(a -> a.getHeight() > 170) .distinct().collect(Collectors.toMap(a -> a.getName(), a -> a.getHeight())); System.out.println(map); // 找出身高超过170的学生对象, 存入数组中 //Object[] arr = students.stream().filter(a -> a.getHeight() > 170).toArray(); //System.out.println(Arrays.toString(arr)); Student[] arr = students.stream().filter(a -> a.getHeight() > 170) .toArray(len -> new Student[len]); System.out.println(Arrays.toString(arr)); } }
Stream流的常见终结方法
最新推荐文章于 2024-11-09 20:55:41 发布