Will Graham Will Graham -4 years ago 208
Java Question

Java 8 list to existing map

I have a map

Map<Id,Map<Obj1,Obj2>> existingMap and List<Obj1> list
;
I need to add list values to map as key and new Map as value.

I tried to do something like:

existingMap.putAll(list.stream().map(x->x.getId()).collect(
Collectors.toMap(x, x -> Map<Obj1,Obj2>::new);


How should I write it? And how can use parameterized constructor against default?

Answer Source

Try:

list.forEach(e -> existingMap.put(e.getId(), new HashMap<>()));

Still uses functional Java 8 features, same effect.

for-loop equivalent:

for(Id id : list)
    existingMap.put(id.getId(), new HashMap<>());

Problems with your code:

  • Map is an interface, and can't be instantiated. Use a concrete implementation like HashMap or TreeMap for example.

  • Collectors#toMap accepts two Functions. If you want to use your format, you'd need:

    Collectors.toMap(x -> x, HashMap::new)   
    

    Notice the lambda x -> x instead of simply x.

    Edit: Of course, you can use Function.identity(), which is more verbose, instead of x -> x, but depending on your needs this may be more expressive.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download