Java 8列表到现有地图

Wil*_*ham 2 java lambda dictionary hashmap java-8

我有一张地图Map<Id,Map<Obj1,Obj2>> existingMap and List<Obj1> list; 我需要添加列表值以映射为键和新Map作为值.

我尝试过这样的事情:

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

我该怎么写呢?如何使用参数化构造函数来防止默认?

Moi*_*ira 10

尝试:

list.forEach(e -> existingMap.put(e.getId(), new HashMap<>()));
Run Code Online (Sandbox Code Playgroud)

仍然使用功能Java 8功能,效果相同.

for-loop当量:

for(Id id : list)
    existingMap.put(id.getId(), new HashMap<>());
Run Code Online (Sandbox Code Playgroud)

代码问题:

  • Map是一个接口,无法实例化.使用类似HashMap或具体的具体实现TreeMap.

  • Collectors#toMap接受两个 Function.如果您想使用您的格式,您需要:

    Collectors.toMap(x -> x, HashMap::new)   
    
    Run Code Online (Sandbox Code Playgroud)

    注意lambda x -> x而不是简单x.

    编辑:当然,您可以使用Function.identity(),而不是更详细x -> x,但根据您的需要,这可能更具表现力.