我有一堆基本上在做相同事情的方法:根据类的不同方法返回的值选择一个类的前N个实例,这些实例都返回双精度值。
例如,对于实现以下接口的类的对象:
interface A {
Double getSalary();
Double getAge();
Double getHeight();
}
我想选择N种对象,每种方法返回的值都最高。
现在我有3种方法:
List<A> getTopItemsBySalary(List<A> elements);
List<A> getTopItemsByAge(List<A> elements);
List<A> getTopItemsByHeight(List<A> elements);
具有这个主体:
List<A> getTopItemsBySalary(List<A> elements, int n) {
return elements.stream()
.filter(a -> a.getSalary() != null)
.sorted(Comparator.comparingDouble(A::getSalary).reversed())
.limit(n)
.collect(Collectors.toList());
}
如何传递方法并且只有一种方法?
答案 0 :(得分:6)
您可以使用将Function
转换为A
的{{1}},例如:
Double
您可以使用:
List<A> getTopItems(List<A> elements, Function<A, Double> mapper, int n) {
return elements.stream()
.filter(a -> null != mapper.apply(a))
.sorted(Comparator.<A>comparingDouble(a -> mapper.apply(a))
.reversed())
.limit(n)
.collect(Collectors.toList());
}
如果期望您的getter总是返回非空值,那么使用List<A> top10BySalary = getTopItems(list, A::getSalary, 10);
List<A> top10ByAge = getTopItems(list, A::getAge, 10);
是更好的类型(但是如果您的ToDoubleFunction
返回值可能为null,它将不起作用):< / p>
Double
答案 1 :(得分:0)
我认为您可以更改函数名称并在条件允许的情况下添加
List<A> getTopItems(List<A> elements, int n, String byWhat) {
if (byWhat.equals("Salary"))
return elements.stream()
.filter(a -> a.getSalary() != null)
.sorted(Comparator.comparingDouble(A::getSalary).reversed())
.limit(n)
.collect(Collectors.toList());
if (byWhat.equals("Height"))
return elements.stream()
.filter(a -> a.getHeight() != null)
.sorted(Comparator.comparingDouble(A::getHeight).reversed())
.limit(n)
.collect(Collectors.toList());
if (byWhat.equals("Age"))
return elements.stream()
.filter(a -> a.getAge() != null)
.sorted(Comparator.comparingDouble(A::getAge).reversed())
.limit(n)
.collect(Collectors.toList());
}
答案 2 :(得分:0)
您可以将字段名称传递给通用的getTopItems函数,并使用java.beans.PropertyDescriptor
List<A> getTopItemsByField(List<A> elements, String field) {
PropertyDescriptor pd = new PropertyDescriptor(field, A.class);
Method getter = pd.getReadMethod();
return elements.stream()
.filter(a -> getter(a) != null)
.sorted(Comparator.comparingDouble(a->a.getter(a)).reversed())
.limit(n)
.collect(Collectors.toList());
}