Java8的流处理stream
程序员文章站
2024-01-09 18:33:34
...
流处理stream结合函数式编程规范,极大提升编程效率,减少代码量;先构造2个对象,student和teacher,teacher拥有多个student对象,经常有类似使用teacher对象后对student操作的场景;
package org.example;
import org.example.model.Student;
import org.example.model.Teacher;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
System.out.println("begin.");
Student a = new Student(1, "001", "zhangsan", "1");
Student b = new Student(2, "001", "lisi", "2");
Student c = new Student(3, "001", "wangwu", "3");
Student d = new Student(4, "001", "mazi", "4");
Student e = new Student(5, "001", "zhaowu", "5");
Student f = new Student(6, "001", "xuliu", "6");
Student g = new Student(7, "001", "dongqi", "7");
Student h = new Student(8, "001", "chenba", "8");
List<Student> studentList = new ArrayList<Student>();
studentList.add(a);
studentList.add(b);
studentList.add(c);
studentList.add(d);
studentList.add(e);
studentList.add(f);
studentList.add(g);
studentList.add(h);
Teacher t1 = new Teacher(1, "12", "boy", "laoshi", studentList);
}
}
map
map通过映射直接拿到属性值,返回的是属性而并非原有对象,有多重写法:
List<Integer> list = t1.getStudentList()
.stream()
.map(Student::getId)
.collect(Collectors.toList());
List<Integer> list1 = t1.getStudentList()
.stream()
.map(student -> student.getId())
.collect(Collectors.toList());
System.out.println(list);
System.out.println(list1);
也可以在取值时候做转换运算:
// map做运算
List<Integer> list2 = t1.getStudentList()
.stream()
.map(student -> {
return student.getId() + 1;
}).collect(Collectors.toList());
System.out.println("list2:" + list2);
filter
filter过滤,返回的是原有对象:
// filter过滤
List<Student> list3 = t1.getStudentList()
.stream()
.filter(student -> {
return student.getId() > 3;
}).filter(student -> {
return student.getName().contains("s");
}).collect(Collectors.toList());
System.out.println("list3:" + list3);
List<Student> list4 = t1.getStudentList()
.stream()
.filter(student -> student.getId() > 2)
.collect(Collectors.toList());
flatmap
flatmap拍扁,跟flink中的流式处理定义相似,输出一对多
// flatmap拍扁,输出值
BinaryOperator<Student> getBiggestID = (x1, x2) -> {
int id1 = x1.getId();
int id2 = x2.getId();
return x1.getId() > x2.getId() ? x1 : x2;
};
Integer maxID = Optional.ofNullable(t1.getStudentList())
.flatMap(students -> students.stream().reduce(getBiggestID))
.map(Student::getId)
.orElse(0);
System.out.println(maxID);
collect
可以流处理同样可以聚合,groubpingby函数为例:
// groupby转化
Map<String,List<Student>> list6 = t1.getStudentList().stream()
.filter(student -> !student.getName().isEmpty())
.collect(Collectors.groupingBy(x->x.getName().contains("s")?"ss":"nn"));
System.out.println(list6);
待续;