Collect keys from List<HashMap> using streams

Viewed 280

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());
2 Answers

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());

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());
Related