stream API 使用大全

一 获取stream流

  第一种 集合直接获取
  List<Student> studentList = student.getStudentList();
  Stream<Student> stream = studentList.stream();
  第二种 Stream.of() 获取
    Stream<Integer> integerStream = Stream.of(1, 2, 3);

二 .map 映射

	//map 映射 获取student 中的 date 值
studentList.stream().map(Student :: getDate).forEach(System.out :: println);

三 筛选和分片
filter 过滤 接受Lambda,从流中排除某些元素

//filter 过滤 获取年龄大于50的 student对象
 studentList.stream().filter(s -> s.getAge() >50).forEach(System.out :: println);
  //姓名长度
 (1)studentList.stream().map(Student::getName).filter(n -> n.length() > 3).forEach(System.out::println);
   (2) studentList.stream().filter(s ->{
         return s.getName().length() > 2;
    }).forEach(System.out::println);

limit(n) 截断流,使元素不超过给定数量

studentList.stream().limit(2).forEach(System.out::println);

skip(n) 跳过元素,扔掉前 n 个元素 如果 n 超过数组长度 返回空

studentList.stream().skip(1).forEach(System.out::println);

筛选 通过对象的 hashCode() 和 equals() 去重

studentList.stream().distinct().forEach(System.out::println);

四 排序

//根据年龄正序排序
studentList.stream().sorted((s1,s2) -> Integer.compare(s1.getAge(),s2.getAge())).forEach(System.out :: println);
 //reversed() 倒序
 studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).forEach(System.out::println);
   //thenComparing()多条件排	序
   studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed().thenComparing(Student::getName).reversed()).forEach(System.out::println);

五 匹配与查找

//获取最大时间
 Date date = studentList.stream().max(Comparator.comparing(Student::getDate)).get().getDate();
 //获取最小时间
Date date1 = studentList.stream().min(Comparator.comparing(Student::getDate)).get().getDate();
// allMatch 判断是否全部符合条件 全部符合返回true 有一个不符合 返回false
boolean b = studentList.stream().allMatch(s -> s.getAge() > 40);
//anyMatch 任意一个符合条件 返回true 全不符合返回false
boolean b1 = studentList.stream().anyMatch(s -> s.getAge() > 70);
//noneMath 是否没有符合条件的  有符合添加的返回false  没有符合条件的返回true
boolean b2 = studentList.stream().noneMatch(s -> s.getName().startsWith("武"));
//获取集合中的第一个对象的名字
String name = studentList.stream().findFirst().get().getName();
//获取集合中的任意一个对象的名字
String name1 = studentList.parallelStream().findAny().get().getName();

六 归约

	//求和
	Integer sum = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).reduce(0, Integer ::sum);
	Integer sum = studentList.stream().map(Student::getAge).reduce(Integer::sum).get();
	Integer sum = studentList.stream().map(Student::getAge).reduce((a1, a2) -> a1 + a2).get();

七 收集

    //收集
    List<String> collect = studentList.stream().map(Student::getName).collect(Collectors.toList());
    Set<String> collect1 = studentList.stream().map(Student::getName).collect(Collectors.toSet());
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值