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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With