Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert list to map using streams and collections?

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading