java8 Stream 史上最全总结
温馨提醒:在电脑上看更方便
(一)stream的特点
一、 流操作都支持 lambda 表达式作为参数 ,函数式编程,充分利用了pipeline 思想
二、无修改 ,无储存
对原始数据无修改,对流和流的中间结果无储存
三 、 惰性执行
四、可以并发执行 , paralleStream
五、 默认只消费一次
1) 巧妙避免代码重复的方式 Supplier
-
Supplier<Stream<String>> streamSupplier = () -> Stream.of("1", "2").filter(t -> t.equals("1"));
-
final Optional<String> any = streamSupplier.get().findAny();//1
-
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
-
final HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
-
final BiConsumer biConsumer = (k, v) -> {
-
System.out.println(k);
-
System.out.println(v);
-
};
-
objectObjectHashMap.forEach(biConsumer);
BiPredicate
-
Path testPath = Paths.get("/Users/qiaozhy/data");
-
//finding files containing 'items' in name
-
final BiPredicate<Path, BasicFileAttributes> items = (path, basicFileAttributes) -> {
-
File file = path.toFile();
-
return !file.isDirectory() &&
-
file.getName().contains("items");
-
};
-
Stream<Path> stream =
-
Files.find(testPath, 100,items
-
);
-
stream.forEach(System.out::println);
3) 扩展的运算符
BinaryOperator 继承BiFunction
-
BinaryOperator<Integer> add = (n1, n2) -> n1 + n2;
UnaryOperator 继承Function
-
UnaryOperator<Integer> dda = x -> x + 1;
(三)stream的操作
一、 流的创建 (最终都是依赖底层的StreamSupport类来完成Stream创建)
1) Collect