<HashMap> 使用流从列表中收集密钥



我有一个名为dataBeanList的List<ExcelData>。ExcelData类具有变量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());

相关内容

最新更新