I have a list of object and want to convert it into map using stream but has generic type resolver to resolve the type argument. Code:
private Map<String,ABCClass<?>> mapToCreate=new HashMap<>();
List<ABCClass<?>> listOfABC;
for(ABCClass<?> vals: listOfABC){
Class<?> typeArgument=(Class<?> GenericTypeResolver.resolveTypeArgument(vals.getClass().getSuperClass(),ABCClass.class));
mapToCreate.put(typeArgument.getSimpleName(),vals);
}
I want to convert above code in collectors and stream enhanced format, is it possible as I am getting an error in toMap function below line stating:
The method toMap() in the type collectors is not applicable for the arguments,
Is there any way to convert it in the map format.
mapToCreate=listOfABC.stream().collect(Collectors.toMap((Class<?> GenericTypeResolver.resolveTypeArgument(listOfABC.getClass().getSuperClass(),ABCClass.class),listOfABC))
>Solution :
Assuming that the code you’ve provided dose it’s job correctly, it implies that the source list contains only one object per type, you can use Collectors.toMap() as shown in the code below. Otherwise, your map.put() is overriding values, and to resolve collisions you have to pass the third argument into Collectors.toMap().
public Map<String, ABCClass<?>> getObjectBySimpleName(List<ABCClass<?>> listOfABC) {
return listOfABC.stream()
.collect(Collectors.toMap(val -> ((Class<?>) GenericTypeResolver.resolveTypeArgument(/*...*/))
.getSimpleName(),
Function.identity()));
}
I am getting an error: The method toMap() in the type collectors is not applicable for the arguments
You defined the map being of type Map<String,ABCClass<?>>, and the type returned by getSuperClass() doesn’t matches the type of key String.