Home > Net >  How can I convert a list of Genric Objects into a Map using streams and collectors
How can I convert a list of Genric Objects into a Map using streams and collectors

Time:03-16

I have a List of objects that have a generic type and want to convert it into a Map using streams. But I need to apply resolver to resolve the type of the 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 the above code into enhanced format by using collectors and streams. Is it possible?

I tried this:

mapToCreate = listOfABC.stream()
            .collect(Collectors.toMap(((Class<?>) GenericTypeResolver.resolveTypeArgument(listOfABC.getClass().getSuperClass(), ABCClass.class), listOfABC)));

I am getting an error in toMap function below line stating:

The method toMap() in the type collectors is not applicable for the arguments

CodePudding user response:

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

1. GenericTypeResolver.resolve...etc. .getSuperClass() is being passed as a keyMapper function into Collectors.toMap(), but it's not a function. The correct syntax should be like this: x -> GenericTypeResolver.do(x). (take a look at this tutorial on lambda expressions)

2. You defined the map being of type Map<String,ABCClass<?>>, and the type returned by getSuperClass() doesn't match the type of key String and you need to apply getSimpleName() to fix it.

  • Related