1

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

Andronicus
  • 25,419
  • 17
  • 47
  • 88
JGFMK
  • 8,425
  • 4
  • 58
  • 92

1 Answers1

3

Let the caller do the mapping by sending in a function (just as map() does):

public static <T> List<String> getStringListOfCollectionProperty(List<T> l, 
      Function<T, String> propMapper) {
        return l.stream().map(propMapper).collect(Collectors.toList());
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • So how would I invoke that? What goes in the function argument in the caller? – JGFMK Feb 04 '20 at 12:30
  • 3
    @JGFMK `List result = getStringListOfCollectionProperty(viewValues, ViewValue::getId);`, for example – Holger Feb 04 '20 at 12:35
  • Have been Googling.. I think this is it.. `Function f = ec -> ec.name;` `List extCal = getListOfTypeUForCollectionTsProperty(this.extendedCalendars, f);` – JGFMK Feb 04 '20 at 12:36
  • Yep. Just tested. And it worked treat. Thanks. Never used Function in Java before. Seen similar stuff in TypeScript/JavaScript/Python. Just never done that in Java before. Cool ;-) (Sourced it from here: https://www.geeksforgeeks.org/function-interface-in-java-with-examples/) – JGFMK Feb 04 '20 at 12:40