koltin中flatMap的使用方法

x33g5p2x  于2022-04-01 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(399)

当时用一个方法,遍历list将查出来的值添加到list并返回list值,如下的代码

  1. private fun getVPCFlowLogs(s3ObjectSummaryList:List<S3ObjectSummary>):List<VPCFlowLog>{
  2. //将所有的文件中的内容合并成一个list,并返回
  3. val vpcFlowLogList = mutableListOf<VPCFlowLog>()
  4. if(s3ObjectSummaryList.isNotEmpty()){
  5. s3ObjectSummaryList.forEach {
  6. vpcFlowLogList.addAll(filterVPCFlowLogs(it))
  7. }
  8. }
  9. return vpcFlowLogList
  10. }

可以使用flatMap 替代,代码如下:

  1. private fun getVPCFlowLogs(s3ObjectSummaryList:List<S3ObjectSummary>):List<VPCFlowLog>{
  2. //如果存在处理多个文件的情况,将所有的文件中的内容合并成一个list,并返回
  3. return s3ObjectSummaryList.flatMap { filterVPCFlowLogs(it) }
  4. }

相关文章