java - 是否可以将“Java 8 方法参考”对象传递给流?
问题描述
我正在寻找一个方法参考,即,Person::getAge
并将其作为参数传递以在流中使用。
因此,与其做一些类似的事情
personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
我想做
sortStream(personList, Person::gerAge)
和排序流方法
public static void sortStream(List<Object> list, ???)
{
list.stream()
.sorted(Comparator.comparing(???))
.collect(Collectors.toList());
}
我一直在环顾四周,发现了两种类型,一种是Function<Object,Object>
,另一种是,Supplier<Object>
但它们似乎都不起作用。
使用供应商或功能时,方法本身似乎很好
sortStream(List<Object>, Supplier<Object> supplier)
{
list.stream()
.sorted((Comparator<? super Object>) supplier)
.collect(Collectors.toList());
}
但是打电话的时候 sortStream(personList, Person::gerAge)
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type:
没有显示真正的错误,所以我不确定 Netbeans 是否存在未检测到错误的问题,或者是什么问题(因为有时会发生这种情况)。
有人对我如何解决这个问题有任何建议吗?非常感谢
解决方案
一个是
Function<Object,Object>
使用Function<Person, Integer>
, 并传入 a List<Person>
:
public static void sortStream(List<Person> list, Function<Person, Integer> fn) { ... }
如果你想让它通用,你可以这样做:
public static <P, C extends Comparable<? super C>> void sortStream(
List<P> list, Function<? super P, ? extends C> fn) { ... }
或者,当然,您可以直接传入 a Comparator<P>
(or Comparator<? super P>
),以明确该参数的用途。
推荐阅读
- docker - 无法获得 D-Bus 连接:不允许操作 [docker]
- css - 图像高度失真
- python - 使用类构造函数来处理图像 tkinter
- javascript - 网页加载时如何自动粘贴复制的文本?
- sql - 如何在 oracle 数据库 SQL-92 标准搜索查询中进行更可靠的搜索?
- java - 单击 Button-java.lang.IllegalStateException 后应用程序崩溃:无法执行 android:onClick 的方法
- javascript - 在反应中从api获取数据
- python - Matplotlib 水平条图(barh):为什么条在顶部而不是彼此相邻?
- winapi - 如何在 Windows 32 位 x86 程序集中获取 EXCEPTION_POINTERS?
- c - 有没有办法在空终止字节之后检查字符串内容?