Convert type X to Y in Map<K, Map<V, X>> using Java Stream API

Viewed 2026

I want to convert inner map from map of maps.

Old map: Map<String, Map<LocalDate, Integer>> Integer means seconds

New map: Map<String, Map<LocalDate, Duration>>

I have tried created new inner map, but got an error

Error: java: no suitable method found for putAll(java.util.stream.Stream<java.lang.Object>) method java.util.Map.putAll(java.util.Map<? extends java.time.LocalDate,? extends java.time.Duration>) is not applicable

oldMap.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                e -> new HashMap<LocalDate, Duration>() {{
                    putAll(
                        e.getValue().entrySet().stream()
                            .map(x -> new HashMap.SimpleEntry<LocalDate, Duration>
                                (x.getKey(), Duration.ofSeconds(x.getValue())))
                    );
                }}
            ));
9 Answers
Related