MXBuster
MXBuster

Reputation: 43

is it possible to pass a " Java 8 Method Reference" object to a stream?

I am looking to take a Method Reference i.e., 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

Upvotes: 1

Views: 464

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

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.

Upvotes: 4

Related Questions