[英]Collect keys from List<HashMap> using streams
我有一个名为 dataBeanList 的List<ExcelData>
。 ExcelData class 具有变量HashMap<String, Integer>
cardNumber。
我想从List<ExcelData>
获取所有键。 我尝试了以下方法,但是我获得了List<List<String>>
值。 但是我想获取List<String>
值。 你能帮我解决这个问题吗?
List<List<String>> collect = dataBeanList
.stream()
.map(excelData ->
excelData.getCardNumber().keySet()
.stream()
.collect(Collectors.toList()))
.collect(Collectors.toList());
基于@ernest_k 在评论中提供的答案(他还谈到了如果键重复并且您只需要不同的键,则使用将其转换为集合):
List<String> collect = dataBeanList
.stream()
.map(excelData ->
excelData.getCardNumber().keySet()
.stream()
.collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toList());
每当您需要从一个 Stream 创建另一种类型的 Stream 时,请使用 flatMap。 从文档 -
Returns a stream consisting of the results of replacing
each element of his stream with the contents of a mapped stream
produced by applying the provided mapping function to each element
将您的代码更改为 -
dataBeanList.stream().
flatMap(excelData -> excelData.getCardNumber().keySet().stream()).
collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.