Skip to content
Advertisement

Java: create copy of ArrayList of HashMaps but include only certain keys

Consider the following data structures:

JavaScript

This code creates a copy of entries, but with hashmaps only including the keys in keyNamesToInclude:

JavaScript

How would one create this with Streams in a functional way?

Advertisement

Answer

It is better to convert keyNamesToInclude into Set to facilitate lookup of the keys.

Then use List::stream to get Stream<HashMap> and for each map get filtered stream of its entries re-collected into a new map and list accordingly.

JavaScript

If it is very important to have concrete implementations of List and Map in copies, casting or special forms of collectors may be needed even though Collectors.toList() returns ArrayList and Collectors.toMap returns HashMap:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement