Stream流
stream流是对集合类的操作工具,通过lambda表达式,对集合进行过滤、查找、遍历等计算。
仅概述工作中常用的一些操作。
创建实体类
public class Student {
private Integer age;
private String name;
private String id;
private String flag;
}
public class MyStream {
public static void main(String[] args) throws InterruptedException {
List<Student> list = new ArrayList<>();
Student stu = new Student();
Student1 student = new Student1();
list.add(new Student(18,"xhj1","1","1"));
list.add(new Student(19,"xhj2","2","1"));
list.add(new Student(16,"xhj3","3","0"));
list.add(new Student(18,"xhj4","11","0"));
list.add(new Student(12,"xhj5","5","1"));
list.add(new Student(20,"xhj6","6","0"));
list.add(new Student(15,"xhj7","7","1"));
list.add(new Student(26,"xhj8","8","0"));
list.add(new Student(24,"xhj9","9","1"));
list.add(new Student(18,"xhj10","10","1"));
}
}
得到集合中 某个属性的最值的对象
Student s = list.stream().max(Comparator.comparingInt(Student::getAge)).get();//获取集合中年龄最大对象
获取集合中的某个属性集合(未去重)
List<Integer> collect = list.stream().map(Student::getAge).collect(Collectors.toList());//获取age集合
去重(distinct)
List<Integer> disCollect = collect.stream().distinct().collect(Collectors.toList());
将集合的某个属性作为map的key,拥有这个属性值的对象作为集合值存储
Map<Integer, List<Student>> collectMap = list.stream().collect(Collectors.groupingBy(e -> e.getAge()));
过滤指定属性对象(准确说是获取)
目前的list对象元素:
list.add(new Student(18,"xhj1","1","1"));
list.add(new Student(19,"xhj2","2","1"));
list.add(new Student(16,"xhj3","3","0"));
list.add(new Student(18,"abc","10","1"));
String a = "xhj";
Map<Integer, List<Student>> collectMap = list.stream().collect(Collectors.groupingBy(e -> e.getAge()));
//过滤指定属性对象(准确说是获取) 获取到name含有xhj的对象
List<Student> collectFilter = list.stream().filter(x -> x.getName().contains(a)).collect(Collectors.toList());
根据指定属性排序 正序
System.out.println(list);
List<Student> ascCollect = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
System.out.println(ascCollect);
倒序( reversed() )
List<Student> descCollect = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
…
后续更新。。。