Java8 Stream 及 常见坑点
所属分类 java8
浏览量 1163
Java8 函数式编程 lambda 方法引用 Stream流
Stream Java8新增的一个接口,以声明性方式处理数据集合
流水线
数据源+零或者多个中间操作+一个终端操作
Stream特点
只能遍历(消费)一次
保护数据源
lazy 中间运算 filter map , 终端操作(如collect)
Stream 创建
Stream strStream = Stream.of("hello", "java8", "stream");
IntStream intStream = IntStream.of(1, 2, 3);
List intList = Arrays.asList(4,5,6);
Stream integerStream = intList.stream();
Integer[] array = {7, 8, 9};
integerStream = Arrays.stream(array);
Random random = new Random();
intStream = random.ints().limit(3);
integerStream = Stream.generate(random::nextInt).limit(3);
// 生成3个奇数
integerStream = Stream.iterate(1, n -> n + 2).limit(3);
Stream pathStream = Files.list(Paths.get("/"));
Stream常用操作
两类操作
中间操作 filter map 等
终端操作 foreach min max count collect 等
List words = Arrays.asList("hello", "java8", "stream");
// 计算每个单词的长度
List list = words.stream().map(String::length).collect(Collectors.toList());
// 5 5 6
list.forEach(System.out::println);
words = Arrays.asList("a", "b-c", "d-e-f");
List list1 = words.stream().map(word -> word.split("-")).collect(Collectors.toList());
list1.forEach(System.out::println);
Stream strStream2 = words.stream().map(word -> word.split("-")).flatMap(Arrays::stream).distinct();
strStream2.forEach(System.out::println);
List words2 = Arrays.asList("hello", "java8", "stream");
words2.stream()
.filter(word -> word.length() > 5)
.collect(Collectors.toList())
.forEach(System.out::println);
List integers = Arrays.asList(7, 9, 8);
integers.stream().max(Integer::compareTo).ifPresent(System.out::println);
常见错误
重复使用流
Stream strStream3 = Stream.of("hello", "java8", "stream");
strStream3.forEach(System.out::println);
// java.lang.IllegalStateException: stream has already been operated upon or closed
try {
strStream3.forEach(System.out::println);
}catch(Exception e) {
System.out.println(e);
}
修改数据源
List strings = Arrays.asList("hello", "java8", "stream");
// java.lang.UnsupportedOperationException
strings.stream()
.map(s -> {
strings.add("world");
return s.toUpperCase();
}).forEach(System.out::println);
完整代码
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/java8/StreamTest4.java
JAVA8 stream 集合处理
上一篇
下一篇
JDK15和ZGC
Java8 Lambda表达式排序实战
java方法引用实例
java方法引用
OSGI与Java模块化之路
Lambda表达式与匿名内部类的区别