Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing overloaded method in Java

There are 2 overloaded methods.
Each of these methods converts a list of one type to a list of a different type. But the first method uses a comparator.

class SomeClass {
    public static <T, G> List<G> toListOfNewType(List<T> inputList,
                                                 Function<T, G> mapperFunction, 
                                                 Comparator<? super G> comparator) {
           return Stream.ofNullable(inputList)
                        .flatMap(List::stream)
                        .map(mapperFunction)
                        .sorted(comparator)
                        .collect(Collectors.toList());
    }
    public static <T, G> List<G> toListOfNewType(List<T> inputList,
                                                 Function<T, G> mapperFunction) {
           return Stream.ofNullable(inputList)
                        .flatMap(List::stream)
                        .map(mapperFunction)
                        .collect(Collectors.toList());
    }
}

As you can see, most of the lines are duplicated. How can I get rid of the second method so that passing null to the first as a comparator will not break it?

In other words, how to make the first work without a comparator?

like image 793
Kyle Bak Avatar asked Jan 25 '23 15:01

Kyle Bak


1 Answers

Use an if statement to check for null:

public static <T, G> List<G> toListOfNewType(List<T> inputList,
                                             Function<T, G> mapperFunction,
                                             Comparator<? super G> comparator) {
    Stream<G> stream = Stream.ofNullable(inputList)
            .flatMap(List::stream)
            .map(mapperFunction);
    if (comparator != null)
        stream = stream.sorted(comparator);
    return stream.collect(Collectors.toList());
}

public static <T, G> List<G> toListOfNewType(List<T> inputList,
                                             Function<T, G> mapperFunction) {
    return toListOfNewType(inputList, mapperFunction, null);
}
like image 196
Andreas Avatar answered Jan 30 '23 04:01

Andreas