java8 Stream 史上最全总结

java8 Stream 史上最全总结

温馨提醒:在电脑上看更方便

(一)stream的特点

一、 流操作都支持 lambda 表达式作为参数 ,函数式编程,充分利用了pipeline 思想

二、无修改 ,无储存

对原始数据无修改,对流和流的中间结果无储存

三 、 惰性执行

四、可以并发执行 , paralleStream

五、 默认只消费一次

1) 巧妙避免代码重复的方式 Supplier

 
  1. Supplier<Stream<String>> streamSupplier = () -> Stream.of("1", "2").filter(t -> t.equals("1"));

  2. final Optional<String> any = streamSupplier.get().findAny();//1

  3. final Optional<String> first = streamSupplier.get().findFirst();//2

六、Map 不支持 stream 流

(二)函数接口简介

1)一元函数式接口

接口 参数 返回类型 描述
Predicate T boolean 断言型接口
Consumer T void 消费型接口
Function T R 函数式接口
Supplier None T 供给型接口

2) 二元函数接口

接口 参数 返回类型 描述
BiFunction T, U R Function的变体
BiConsumer T, U void Consumer的变体
BiPredicate T, U boolean Predicate的变体

BiConsumer

 
  1. final HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();

  2. final BiConsumer biConsumer = (k, v) -> {

  3. System.out.println(k);

  4. System.out.println(v);

  5. };

  6. objectObjectHashMap.forEach(biConsumer);

BiPredicate

 
  1. Path testPath = Paths.get("/Users/qiaozhy/data");

  2. //finding files containing 'items' in name

  3. final BiPredicate<Path, BasicFileAttributes> items = (path, basicFileAttributes) -> {

  4. File file = path.toFile();

  5. return !file.isDirectory() &&

  6. file.getName().contains("items");

  7. };

  8. Stream<Path> stream =

  9. Files.find(testPath, 100,items

  10. );

  11. stream.forEach(System.out::println);

3) 扩展的运算符

BinaryOperator 继承BiFunction

 

  1. BinaryOperator<Integer> add = (n1, n2) -> n1 + n2;

UnaryOperator 继承Function

 
  1. UnaryOperator<Integer> dda = x -> x + 1;

(三)stream的操作

一、 流的创建 (最终都是依赖底层的StreamSupport类来完成Stream创建)

1) Collect

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值