Search code examples
javagenericsjava-stream

Using java generics for 2 methods having same operation with different objects while performing stream and related operations


I have 2 functions which are doing the same operations for 2 lists of different object types I am new to generics and trying to create a generic method for the below function.

If someone can help on how I can use generics for map, comparator function I would really appreciate it

public static List<Long> function1(List<Object1> object1) {
return object1.stream().map(Object1::getParameter1)
       sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
public static List<Long> function2(List<Object2> object2) {
return object2.stream().map(Object2::getParameter1)
       sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
public static <T> List<T> function2(List<T> object) {
return new code
}

Solution

  • You can do this, but you may decide that it's more awkward than just having your two different functions. This assumes you always want the sort in descending order:

    public static <T, U extends Comparable<? super U>> List<U> function2(
        List<T> list, Function<T, U> getter) {
      return list.stream().map(getter)
           .sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    }
    

    You would call this like

    public static List<Long> function1(List<Object1> object1) {
      return function2(object1, Object1::getParameter1);
    }
    

    Alternately, if you want to control the sort:

    public static <T, U> List<U> function2(
        List<T> list, Function<T, U> getter, Comparator<? super U> comparator) {
      return list.stream().map(getter).sorted(comparator).collect(Collectors.toList());
    }
    

    You would call this like:

    public static List<Long> function1(List<Object1> object1) {
      return function2(object1, Object1::getParameter1, Comparator.reverseOrder());
    }