Inversion of control in lambda

Viewed 202

I am trying to convert a list into the keys of a Map, and having default values of null.
However, my code requires the creation of a HashMap via the new keyword that goes against the principle of Inversion of Control in Spring.

May I know if there is any right way in Spring to initialize the map in this situation?

convertStringToList(input).stream().collect(HashMap::new, 
             (map, value) -> map.put(value, null), Map::putAll);
2 Answers

The Spring bean autowiring is a bit different than an instantiation of a particular implementation of-non Spring configured components. Don't be afraid of the new keyword and a certain implementation.

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

This is fine since you collect the Stream into a Map, which is an interface. The Spring has no influence to which implementation will be used on the stream collecting, thus you have to specify that HashMap will be used (and not TreeMap for instance...).

If you do...

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

Here you "Cannot instantiate the type Map" - it needs implementation and it's not the Spring's responsibility to provide one.

You shouldn't use manual instantiation for Spring specific beans such as repositories, services, configuration classes and such.
However, it's perfectly normal to manually instantiate instances of maps and collection classes to implement your domain logic.

Related