简体   繁体   中英

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.

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

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.

The method itself seemed to be fine when using either a supplier or Function

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

but when calling 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).

Does anyone have any advice on how I can solve this issue? Thank you very much

one is Function<Object,Object>

Use Function<Person, Integer> , and pass in a List<Person> too:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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