简体   繁体   English

是否可以将“Java 8 方法参考”object 传递给 stream?

[英]is it possible to pass a “ Java 8 Method Reference” object to a stream?

I am looking to take a Method Reference ie, Person::getAge and pass it as a parameter to use in a stream.我希望获取方法参考,即Person::getAge并将其作为参数传递以在 stream 中使用。

So instead of doing something along the lines of因此,与其做一些类似的事情

personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());

I am looking to do我想做

 sortStream(personList, Person::gerAge)

and the sort Stream Method和排序 Stream 方法

public static void sortStream(List<Object> list, ???)
{

        list.stream()
            .sorted(Comparator.comparing(???))
            .collect(Collectors.toList());
}

I have been looking around and found 2 types, one is Function<Object,Object> and the other is Supplier<Object> but none of them seemed to work.我一直在环顾四周,发现了 2 种类型,一种是Function<Object,Object> ,另一种是Supplier<Object>但它们似乎都不起作用。

The method itself seemed to be fine when using either a supplier or Function使用供应商或 Function 时,该方法本身似乎很好

 sortStream(List<Object>, Supplier<Object> supplier)
    {
     list.stream()
         .sorted((Comparator<? super Object>) supplier)
         .collect(Collectors.toList());
    
    }

but when calling sortStream(personList, Person::gerAge)但是当调用sortStream(personList, Person::gerAge)

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type:

There is no real error being shown so I'm not sure if there's an issue with Netbeans not detecting the error, or what (as this sometimes happens).没有显示真正的错误,所以我不确定 Netbeans 是否存在未检测到错误的问题,或者是什么问题(因为有时会发生这种情况)。

Does anyone have any advice on how I can solve this issue?有人对我如何解决这个问题有任何建议吗? Thank you very much非常感谢

one is Function<Object,Object>一个是Function<Object,Object>

Use Function<Person, Integer> , and pass in a List<Person> too:使用Function<Person, Integer> ,并传入List<Person>

public static void sortStream(List<Person> list, Function<Person, Integer> fn) { ... }

If you want to make it generic, you could do:如果你想让它通用,你可以这样做:

public static <P, C extends Comparable<? super C>> void sortStream(
    List<P> list, Function<? super P, ? extends C> fn) { ... }

Or, of course, you could pass in a Comparator<P> (or Comparator<? super P> ) directly, to make it clear what that parameter is for.或者,当然,您可以直接传入Comparator<P> (或Comparator<? super P> ),以明确该参数的用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM