使用Java8 的Stream流操作集合
List<String> fruitList=Stream
.of("apple","banana","coconut","Damson","Filbert","Lemon")
.collect(Collectors.toList());
List<String> meatList=Stream
.of("beef","pork","chicken","lamp","oyster","salmon","tuna")
.collect(Collectors.toList());
List<List<?>> bigList=Stream.of(fruitList,meatList).collect(Collectors.toList());
我想 使用flatMap方法 摊平集合 然后在使用reduce规约最长的一个字符串
bigList.stream().flatMap(x->x.stream()
.reduce((String x,String y)->x.length()>y.length()?x:y)
.ifPresent(System.out::println);
结果报错
错误信息 如图
这个错误是什么 capture of ?
也没见哪篇Stream的文章里讲过
如果把代码改成
bigList.stream().flatMap(x->x.stream())
.map(x->x+"")
.reduce((String x,String y)->x.length()>y.length()?x:y)
.ifPresent(System.out::println);
这样就可以了
如果
bigList.stream().flatMap(x->x.stream()).forEach(System.out::println)
这行代码也可以正常运行,依次两个集合合并后的所有元素
这样看 bigList.stream().flatMap(x->x.stream())
返回的的应该是
所有元素的集合啊
为什么不能后面直接使用reduce方法?
报错的主要原因其实是因为
flatMap
方法里需要的参数,你可以看到其实是一个Function
,而
Function
返回的值是一个Stream
,所以直接填一个s.stream()
显然是满足这个参数要求的..但是s.stream
之后再用了reduce
,reduce
返回的是一个Optional
当然就不满足要求了,所以编译报错
当然如果题主最终是把两个
stream
合在一起,可以不要用Stream.of
方法,可以考虑哈由于之前两个stream
里的类型一样,可以直接用Stream.contact
,就不用摊平了,直接就是平的