java - 如何将方法作为参数传入
问题描述
我有一堆基本上做同样事情的方法:根据不同方法返回的值选择一个类的前 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());
}
我怎样才能传入方法并且只有一种方法?
解决方案
您可以使用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());
}
推荐阅读
- ios - 从 MOV 转换为 MP4 文件后,在 AWS S3 中上传为 0 字节文件
- python - 发送UDP组播报文时设置源地址
- android - notifyListeners() 在循环中运行
- c# - 执行适用于个人访问令牌,但不适用于 Azure DevOps 的 AAD 访问令牌
- python - VScode 的 Python Linter 安装问题
- python - python matplotlib lineplot 基于百分比变化的渐变颜色
- swiftui - 如何在 SwiftUI 中创建超链接
- android - 如何使用 Android Kotlin 实现类似于 YouTube 和 Instagram 的正确导航
- r - 相应地更改颜色
- javascript - 如何使用 ASP.NET MVC 检查浏览器是否支持 HTML5 和 CSS3 功能?