lambda中的控制反转

new*_*111 3 java lambda spring inversion-of-control java-stream

我试图将列表转换为a的键Map,并具有null的默认值.
但是,我的代码需要HashMap通过new关键字创建一个违反Spring中控制反转原理的关键字.

我是否知道在这种情况下Spring是否有正确的方法来初始化地图?

convertStringToList(input).stream().collect(HashMap::new, 
             (map, value) -> map.put(value, null), Map::putAll);
Run Code Online (Sandbox Code Playgroud)

Nik*_*las 5

Spring bean自动装配与非Spring配置组件的特定实现的实例化略有不同.不要害怕new关键字和某个实现.

Map<String, String> newMap = convertStringToList(input).stream().collect(HashMap::new, 
         (map, value) -> map.put(value, null), Map::putAll);
Run Code Online (Sandbox Code Playgroud)

这很好,因为你收集Stream到a Map,这是一个接口.Spring不会影响将在流收集上使用哪个实现,因此您必须指定HashMap将使用的(而不是TreeMap例如......).

如果你这样做......

 Map<String, String> a = b.stream().collect(Map::new, 
         (map, value) -> map.put(value, null), Map::putAll);
Run Code Online (Sandbox Code Playgroud)

在这里你" Cannot instantiate the type Map" - 它需要实现,并且Spring不负责提供一个.