在Java中,涉及到对数组、Collecction等集合类中的元素进行操作的时候,通常会通过循环的方式进行逐个处理,或者使用Stream流的方式进行处理
从给定句子中返回单词长度大于5的单词列表,按长度倒序输出,最多返回3个
public static List<String> sortGetTop3LongWords(@NotNull String sentence) {
return Arrays.stream(sentence.split(","))
.filter(word -> word.length() > 5)
.sorted((o1, o2) -> o2.length() - o1.length())
.limit(3)
.collect(Collectors.toList());
}
Stream流操作分为3种类型:
每个Stream管道操作类型都包含若干个API方法,先列举下各个API方法的功能介绍
主要负责新建一个Stream流,或者基于现有的数组、List、Set、Map等集合类型对象创建出新的Stream流
负责对Stream流进行处理操作,并返回一个新的Stream对象,中间管道操作可以进行叠加
通过终止管道操作之后,Stream流将会结束,最后可能会执行某些逻辑处理,或者是按照要求返回某些执行后的结果数据
map与flatMap都是用于转换已有的元素为其他元素,区别点在于:
flatMap例子:现有一个句子列表,需要将句子中每个单词都提取出来得到一个所有单词列表
public static List<String> stringToIntFlatmap() {
List<String> sentences = Arrays.asList("hello world", "Jia Gou Wu Dao");
return sentences.stream()
.flatMap(sentence -> Arrays.stream(sentence.split(" ")))
.collect(Collectors.toList());
}
stringToIntFlatmap().forEach(System.out::println);
这里需要补充一句,flatMap操作的时候其实是先每个元素处理并返回一个新的Stream,然后将多个Stream展开合并为了一个完整的Stream,如下:
peek和foreach,都可以用于对元素进行遍历然后逐个的进行处理
但根据前面的介绍,peek属于中间方法,而foreach属于终止方法。这也就意味着peek只能作为管道中途的一个处理步骤,而设法直接执行得到结果,其后面必须还要有其它终止操作的时候才会被执行;而foreach作为无返回值的终止方法,则可以直接执行相关操作
public static void testPeekAndForeach() {
List<String> sentences = Arrays.asList("hello world", "Jia Gou Wu Dao");
// 仅peek操作,最终不会执行
System.out.println("----before peek----");
sentences.stream().peek(sentence -> System.out.println(sentence));
System.out.println("----after peek----");
// 仅foreach操作,最终会执行
System.out.println("----before foreach----");
sentences.stream().forEach(sentence -> System.out.println(sentence));
System.out.println("----after foreach----");
// peek操作后面增加终止操作,peek会执行
System.out.println("----before peek and count----");
sentences.stream().peek(sentence -> System.out.println(sentence)).count();
System.out.println("----after peek and count----");
}
输出结果可以看出,peek独自调用时并没有被执行,但peek后面加上终止操作之后便可以被执行,而foreach可以直接被执行
这里需要补充提醒下,一旦一个Stream被执行了终止操作之后,后续便不可以再读这个流执行其他的操作了,否则会报错
public static void testHandleStreamAfterClosed() {
List<String> ids = Arrays.asList("205","10","308","49","627","193","111", "193");
Stream<String> stream = ids.stream().filter(s -> s.length() > 2);
System.out.println(stream.count());
System.out.println("-----下面会报错-----");
// 判断是否有元素等于205
try {
System.out.println(stream.anyMatch("205"::equals));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("-----上面会报错-----");
}
因为Stream已经被执行count()终止方法了,所以多Stream再执行anyMatch方法的时候,就会报错,这里需要特别注意。
public static void testNumberCalculate() {
List<Integer> ids = Arrays.asList(10, 20, 30, 40, 50);
// 计算平均值
Double avg = ids.stream().collect(Collectors.averagingInt(value -> value));
System.out.println("平均值:" + avg);
// 数据统计信息
IntSummaryStatistics summary = ids.stream().collect(Collectors.summarizingInt(value -> value));
System.out.println("数据统计信息:" + summary);
}
上面的例子中,使用collect()方法来对list中元素值进行数学运算:结果如下:
使用并行流,可以有效利用计算机的多CPU硬件,提升逻辑的执行速度。并行流通过将一整个stream划分为多个片段,然后对各个分片流并行执行处理逻辑,最后将各个分片流的执行结果汇总为一个整体流
并行流类似于多线程在并行处理,所以与多线程场景相关的一些问题同样会存在,比如死锁等问题,所以在并行流终止执行的函数逻辑,必须要保证线程安全
Stream流相较于传统的foreach的方式处理stream,到底有啥优势?
根据前面的介绍,我们应该可以得出如下几点答案:
当然了,Stream流也不全是优点,在有些方面也有其弊端: