javahashmapjava-streamlinkedhashmap

Collect stream of EntrySet to LinkedHashMap


I want to collect the stream to a LinkedHashMap<String, Object>.

I have a JSON resource that is stored in LinkedHashMap<String, Object> resources. Then I filter out JSON elements by streaming the EntrySet of this map. Currently I am collecting the elements of stream to a regular HashMap. But after this I am adding other elements to the map. I want these elements to be in the inserted order.

final List<String> keys = Arrays.asList("status", "createdDate");

Map<String, Object> result = resources.entrySet()
        .stream()
        .filter(e -> keys.contains(e.getKey()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

result.put("date", "someDate");
return result;

That is why I want to collect the stream to a LinkedHashMap<String, Object>. How can I achieve this?


Solution

  • You can do this with Stream:

    Map<String, Object> result = resources.entrySet()
                .stream()
                .filter(e -> keys.contains(e.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new));
    

    The part (x, y) -> y is because of mergeFunction when find duplicate keys, it returns value of second key which found. the forth part is mapFactory which a supplier providing a new empty Map into which the results will be inserted.