java+8+stream+赋值_Java8 Stream 使用

Stream 接口

所在包:import java.util.stream.Stream;

A sequence of elements supporting sequential and parallel aggregate operations.

Stream 是元素的集合,类似Iterator

支持顺序和并行的聚合操作

Iterator VS Stream

Iterator,用户只能一个一个的遍历元素并对其执行某些操作

Stream,用户只要给出需要对其包含的元素执行什么操作,比如“过滤掉长度大于10的字符串”、“获取每个字符串的首字母”等,具体这些操作如何应用到每个元素上,都由 Stream 完成

使用Stream的基本步骤

创建 Stream

通过 Stream 接口的静态工厂方法 (注意:Java8里接口可以带静态方法)

通过 Collection 接口的默认方法 stream(),把一个 Collection 对象转换成Stream (较常用)

转换 Stream,每次转换原有Stream对象不改变,返回一个新的Stream对象

对 Stream 进行聚合(Reduce)操作

Stream 的转换

distinct 对 Stream 中包含的元素进行去重操作

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

list.stream().distinct().forEach((s) -> {System.out.print(s + " ");});

filter(Predicate super T> predicate) 对 Stream 中包含的元素使用给定的过滤函数进行过滤操作

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

list.stream().filter((s) -> s != null).forEach((s) -> {System.out.print(s + " ");});

map(Function super T, ? extends R> mapper) 对 Stream 中包含的元素使用给定的转换函数进行转换操作

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

list.stream().filter((s) -> s != null).map((s) -> s + 1).forEach((s) -> {

System.out.print(s + " ");

});

limit(long maxSize) 对一个 Stream 进行截断操作,获取其前 N 个元素

skip(long n) 返回一个丢弃原 Stream 的前 N 个元素后剩下元素组成的新 Stream

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

list.stream().filter((s) -> s != null).limit(2).forEach((s) -> {

System.out.print(s + " ");

});

对 Stream 进行聚合(Reduce)操作

sum() max() count()

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

IntStream is = list.stream().filter((s) -> s != null).mapToInt(Integer::intValue);

System.out.println(is.max());

collect

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

List result = list.stream().filter((s) -> s != null).collect(Collectors.toList());

result.forEach((s) -> {

System.out.print(s + " ");

});

reduce(BinaryOperator accumulator)

sum() max() count() 等都可以使用 reduce() 实现

reduce 方法接受一个函数,这个函数有两个参数:

第一个参数 s1 是上次函数执行的返回值(也称为中间结果)

第二个参数 s2 是 stream 中的元素,这个函数把这两个值相加,得到的和会被赋值给下次执行这个函数的第一个参数

第一次执行的时候第一个参数的值是 Stream 的第一个元素,第二个参数是 Stream 的第二个元素。

这个方法返回值类型是Optional。

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

Optional op = list.stream().filter((s) -> s != null).reduce((s1, s2) -> s1 + s2);

System.out.println(op.get()); // 相当于求和

搜索相关

allMatch 是不是Stream中的所有元素都满足给定的匹配条件

anyMatch Stream中是否存在任何一个元素满足匹配条件

findFirst 返回Stream中的第一个元素,如果Stream为空,返回空Optional

noneMatch 是不是Stream中的所有元素都不满足给定的匹配条件

List list = Arrays.asList(1, null, 1, 2, null, 5, 3, 9, 7);

System.out.println(list.stream().filter((s) -> s != null).allMatch((s) -> s > 0));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值