Array|5万字:Stream和Lambda表达式最佳实践2( 二 )
假如我们有这样两个list:List
list = Arrays.asList("jack", "bob", "alice", "mark");List
duplicateList = Arrays.asList("jack", "jack", "alice", "mark");复制代码
上面一个是无重复的list , 一个是带重复数据的list 。接下来的例子我们会用上面的两个list来讲解Collectors的用法 。9.1 Collectors.toList()List
listResult = list.stream().collect(Collectors.toList());log.info("{}",listResult);复制代码
将stream转换为list 。这里转换的list是ArrayList , 如果想要转换成特定的list , 需要使用toCollection方法 。9.2 Collectors.toSet()Set
setResult = list.stream().collect(Collectors.toSet());log.info("{}",setResult);复制代码
toSet将Stream转换成为set 。这里转换的是HashSet 。如果需要特别指定set , 那么需要使用toCollection方法 。
因为set中是没有重复的元素 , 如果我们使用duplicateList来转换的话 , 会发现最终结果中只有一个jack 。Set
duplicateSetResult = duplicateList.stream().collect(Collectors.toSet());log.info("{}",duplicateSetResult);复制代码9.3 Collectors.toCollection()
上面的toMap,toSet转换出来的都是特定的类型 , 如果我们需要自定义 , 则可以使用toCollection()List
custListResult = list.stream().collect(Collectors.toCollection(LinkedList::new));log.info("{}",custListResult);复制代码
上面的例子 , 我们转换成了LinkedList 。9.4 Collectors.toMap()
toMap接收两个参数 , 第一个参数是keyMapper , 第二个参数是valueMapper:Map
mapResult = list.stream().collect(Collectors.toMap(Function.identity(), String::length));log.info("{}",mapResult);复制代码
如果stream中有重复的值 , 则转换会报IllegalStateException异常:Map
duplicateMapResult = duplicateList.stream().collect(Collectors.toMap(Function.identity(), String::length));复制代码
怎么解决这个问题呢?我们可以这样:Map
duplicateMapResult2 = duplicateList.stream().collect(Collectors.toMap(Function.identity(), String::length, (item, identicalItem) -> item));log.info("{}",duplicateMapResult2);复制代码
在toMap中添加第三个参数mergeFunction , 来解决冲突的问题 。9.5 Collectors.collectingAndThen()
collectingAndThen允许我们对生成的集合再做一次操作 。List
collectAndThenResult = list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), l -> {return new ArrayList(l);}));log.info("{}",collectAndThenResult);复制代码9.6 Collectors.joining()
Joining用来连接stream中的元素:String joinResult = list.stream().collect(Collectors.joining());log.info("{}",joinResult);String joinResult1 = list.stream().collect(Collectors.joining(" "));log.info("{}",joinResult1);String joinResult2 = list.stream().collect(Collectors.joining(" ", "prefix","suffix"));log.info("{}",joinResult2);复制代码
可以不带参数 , 也可以带一个参数 , 也可以带三个参数 , 根据我们的需要进行选择 。9.7 Collectors.counting()
counting主要用来统计stream中元素的个数:Long countResult = list.stream().collect(Collectors.counting());log.info("{}",countResult);复制代码9.8 Collectors.summarizingDouble/Long/Int()
SummarizingDouble/Long/Int为stream中的元素生成了统计信息 , 返回的结果是一个统计类:IntSummaryStatistics intResult = list.stream().collect(Collectors.summarizingInt(String::length));log.info("{}",intResult);复制代码
推荐阅读
- Array|臭氧层正在愈合,并对大气环流造成重大影响
- Array|瞄准“宅经济”!VR看房成年轻人租房新趋势
- Array|Spanlite公司使用3D打印一次高速烧结8,000个零件
- Array|面面俱到的绝佳体验 优质国产旗舰手机推荐
- Array|消息称爱奇艺或在港二次上市,回应称不予置评
- Array|中国移动首次招标边缘计算服务器 浪潮NE5260M5成功中标
- Array|远程课程“育见”VR 联想带来550个STEM教育模块
- Array|宁德时代拟190亿元展开产业链投资,提升公司市场竞争力
- Array|SA:2020年Q2全球智能音箱销量达3000万台,环比增长6%
- Array|GE超滤膜的材质特点
