mardi 4 février 2020

Java 8 Generalised way map a collection of objects for a given property passed as string

I was reviewing this question here and specifically this answer.

List<Long> ids = viewValues.stream().map(ViewValue::getId).collect(Collectors.toList());

I was wondering if this can somehow be adapted to make a generalised utility method, but I am stuck on the syntax for the map part and using some sort of Reflection to get the getter name via a String.

Can someone give me some pointers as to whether this is feasible, and how to fix this code?

public static List<String> getStringListOfCollectionProperty(List<T> l, String propName) {
        return l.stream().map(T::propName).collect(Collectors.toList());
}

Thanks in advance.

PS: I am not allowed to use 3rd party libraries.. like Guava etc..





Aucun commentaire:

Enregistrer un commentaire