collectingAndThen的使⽤姿势
public class AdvancedStreamingP2 {编织篮子
实践报告题目public static void main(String[] args) {
List<Student> studentList = ateData();
collect(studentList);
collectingAnd(studentList);
}
private static void collect(List<Student> studentList) {
System.out.println("\n---------- Extracting Student Name with Max Age by Type -----------");
Map<String, Optional<Student>> stuMax = studentList.stream().collect(groupingBy(Student::getType, maxBy(comparing(Student::getAge)))); stuMax.forEach((k, v) -> System.out.println("Key : " + k + ", Value :" + v.get()));
}
/**
* I want to extract the student name, with the max age, grouping student by Type. Is it possible by using any combination in "collect" itlf?
*
* I want the output like :
*
* ---------- Extracting Student Name with Max Age by Type -----------
*
鹿角胶的功效
* Key : School, Value : Aman
总是玉关情打一字* Key : College, Value : Ajay
*/
private static void collectingAnd(List<Student> studentList) {
Map<String, String> stuMax =
studentList.stream()
.collect(groupingBy(
Student::getType,
collectingAndThen(maxBy(comparing(Student::getAge)),v -> v.get().getName())
跳绳的正确姿势));
System.out.println(stuMax);
}
}
public class Student{
String name;
int age;
String type;
public Student(){}
public Student(String name, int age, String type) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void tName(String name) {
this.name = name;
}
public int getAge() {
蓝色心情return age;
}
public void tAge(int age) {
this.age = age;
}
public String getType() {
return type;
}
public void tType(String type) {
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", type='" + type + '\'' +
'}';
}
public static List<Student> generateData() {
List<Student> st = Arrays.asList(new Student("Ashish", 27, "College"),
春节简笔画new Student("Aman", 24, "School"),
new Student("Rahul", 18, "School"),
new Student("Ajay", 29, "College"),
new Student("Mathur", 25, "College"),婚内财产公证
new Student("Modi", 28, "College"),
new Student("Prem", 15, "School"),
new Student("Akash", 17, "School"));
return st;
}
}
collect⽅法输出参数较多,优化后的collectingAnd⽅法使⽤了collectingAndThen,
顾名思义,即收集并处理,处理函数是 Function功能函数,即输⼊⼀个参数,并返回⼀个参数