Type cast for inner HashMap to Map

Viewed 177

Can I typecast a complex structure like HashMap<String,List<HashMap<String,String>>> to Map<String,List<Map<String,String>>> ?

2 Answers

I would recommend stream the outer and inner map and then assign to parent reference Map

 Map<String,List<hMap<String,String>>> res = map.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                    entry->entry.getValue().stream().map(HashMap::new).collect(Collectors.toList())));

A List<HashMap<String,String>> is not a List<Map<String,String>>. You can pretend and use the raw type at your own risk:

HashMap<String, List<HashMap<String,String>>> map = new HashMap<>();
Map<String,List<Map<String,String>>> cast = (Map) map;

You'll get a warning for unchecked assignment, because you can then do this:

String key = "";
cast.put(key, Collections.singletonList(new TreeMap<>())); // Not a HashMap
HashMap<String, String> inserted = map.get(key).get(0);

This compiles with no warning but will throw a ClassCastException.

Related