英文:
Collect keys from List<HashMap> using streams
问题
我有一个名为 dataBeanList
的 List<ExcelData>
。ExcelData
类拥有变量 HashMap<String, Integer>
cardNumber
。
我想从 List<ExcelData>
中获取所有的键(keys)。我尝试了下面的方法,但是我得到了 List<List<String>>
类型的值。然而,我希望得到 List<String>
类型的值。你能帮我解决这个问题吗?
List<List<String>> collect = dataBeanList
.stream()
.map(excelData ->
excelData.getCardNumber().keySet()
.stream()
.collect(Collectors.toList()))
.collect(Collectors.toList());
英文:
I have a List<ExcelData>
called dataBeanList. ExcelData class has variable HashMap<String, Integer>
cardNumber.
I want to get all keys from List<ExcelData>
. I tried below approach but, I obtained List<List<String>>
values. However I want to get List<String>
values. Can you help me with that?
List<List<String>> collect = dataBeanList
.stream()
.map(excelData ->
excelData.getCardNumber().keySet()
.stream()
.collect(Collectors.toList()))
.collect(Collectors.toList());
答案1
得分: 3
基于 @ernest_k 在评论中提供的答案(他还谈到如果键重复并且您只需要不同的键,则可以将其转换为集合):
List<String> collect = dataBeanList
.stream()
.map(excelData ->
excelData.getCardNumber().keySet()
.stream()
.collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toList());
英文:
Building on what @ernest_k provided as answer in comment (he also talked about using converting it to a set if the keys are duplicating and you need only distinct ones) :
List<String> collect = dataBeanList
.stream()
.map(excelData ->
excelData.getCardNumber().keySet()
.stream()
.collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toList());
答案2
得分: 3
使用flatMap
,每当你需要从一个流创建另一种类型的流时,就可以使用它。
根据文档说明:
返回一个流,该流由将此流的每个元素替换为映射流的内容所组成,映射流是通过将提供的映射函数应用于每个元素而生成的。
将你的代码更改为:
dataBeanList.stream()
.flatMap(excelData -> excelData.getCardNumber().keySet().stream())
.collect(Collectors.toList());
英文:
Use flatMap whenever you need to create another type of Stream from one Stream.
From documentation -
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
Change your code to -
dataBeanList.stream().
flatMap(excelData -> excelData.getCardNumber().keySet().stream()).
collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论