stream的常用操作

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());


后续更新。。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值