首页 > 解决方案 > 如何将方法作为参数传入

问题描述

我有一堆基本上做同样事情的方法:根据不同方法返回的值选择一个类的前 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());
}

我怎样才能传入方法并且只有一种方法?

标签: java

解决方案


您可以使用Function转换A为的 a 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());
}

您可以使用以下方法调用它:

List<A> top10BySalary = getTopItems(list, A::getSalary, 10);
List<A> top10ByAge = getTopItems(list, A::getAge, 10);

如果您的 getter 应该总是返回一个非空值,那么使用更好的类型(但如果您的返回值可能为空值ToDoubleFunction,它将不起作用):Double

List<A> getTopItems(List<A> elements, ToDoubleFunction<A> mapper, int n) {
    return elements.stream()
              .sorted(Comparator.comparingDouble(mapper).reversed())
              .limit(n)
              .collect(Collectors.toList());
}

推荐阅读