Java Stram 流对于返回对象的处理 (结束流)
package com.zhong.streamdemo.showdownstreamdemo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ShowDownStream {public static void main(String[] args) {ArrayList<Student> students = new ArrayList<>(List.of(new Student("小钟", 22, 179.1),new Student("小钟", 22, 179.1),new Student("小王", 21, 153.9),new Student("小王", 21, 153.9),new Student("张三", 52, 160.8),new Student("李四", 42, 140.5),new Student("王五", 18, 135.3)));System.out.println("-------------计算出升高超过 153 的有多少-------------");long count = students.stream().filter(x -> x.getHeight() > 153).count();System.out.println(count);System.out.println("-------------找出身高最高的学生对象并输出-------------");Student student = students.stream().max(Comparator.comparingDouble(Student::getHeight)).get();System.out.println(student);System.out.println("-------------计算出升高超过 153 的对象并放到一个新的集合返回-------------");List<Student> collect = students.stream().filter(x -> x.getHeight() > 153).toList();collect.forEach(System.out::println);System.out.println("-------------计算出升高超过 153 的对象 把姓名和身高放到一个新的 Map 集合返回-------------");Map<String, Double> collect1 = students.stream().filter(x -> x.getHeight() > 153).distinct() .collect(Collectors.toMap(Student::getName, Student::getHeight));collect1.forEach((k, v) -> System.out.println(k + " ==> " + v));System.out.println("-------------5、找出身高最高的学生对象 收集到学生数组-------------");Student[] array = students.stream().filter(x -> x.getHeight() > 153).toArray(Student[]::new);for (Student student1 : array) {System.out.println(student1);}}
}@Data
@AllArgsConstructor
@NoArgsConstructor
class Student {private String name;private int age;private double height;@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return age == student.age && Double.compare(height, student.height) == 0 && Objects.equals(name, student.name);}@Overridepublic int hashCode() {return Objects.hash(name, age, height);}
}