是否可以将“Java8方法引用”对象传递给流?

ndasle7k  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(351)

我正在寻找一个方法参考,即。, 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没有检测到错误是否有问题,或者是什么问题(有时会发生这种情况)。
有人对我如何解决这个问题有什么建议吗?非常感谢你
nqwrtyyt

nqwrtyyt1#

一个是 Function<Object,Object> 使用 Function<Person, Integer> ,并通过 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) { ... }

当然,你也可以通过 Comparator<P> (或 Comparator<? super P> )直接地,弄清楚那个参数是用来做什么的。

相关问题