删除Java中的重载方法 [英] Removing overloaded method in Java
本文介绍了删除Java中的重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有2个重载方法.
每个方法都将一种类型的列表转换为另一种类型的列表.但是第一种方法使用比较器.
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());
}
}
如您所见,大多数行都是重复的.如何摆脱第二种方法,以便将null作为比较器传递给第一种方法不会破坏它?
换句话说,如何在没有比较器的情况下使第一个工作正常?
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?
推荐答案
使用if
语句检查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);
}
这篇关于删除Java中的重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文