首页 > 解决方案 > 是否可以将“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 是否存在未检测到错误的问题,或者是什么问题(因为有时会发生这种情况)。

有人对我如何解决这个问题有任何建议吗?非常感谢

标签: javajava-8java-streammethod-reference

解决方案


一个是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>),以明确该参数的用途。


推荐阅读