-1

When using java stream show error while coding

Optional.ofNullable(product.getStudents())
                .orElseGet(Collections.emptyList())
                .stream().map(x->x.getId)
                .collect(Collectors.toList());

this code shows below error ERROR

incompactible type, Required Supplier> but empty list was interfered to List : no instance of type variable of T exist so List conforms to Supplier>

But if I replace the Collections.emptyList() WITH Collections::emptyList It will be perfect.

What is the difference between Collections.emptyList() vs Collections::emptyList?

Jaime S
  • 1,488
  • 1
  • 16
  • 31
Araf
  • 510
  • 8
  • 32
  • 4
    short: first is an expression calling that method, second is a reference to that method (call is *delayed*, or eventually not called at all) BTW probably `x->x.getId()` could be susbstitued by `Student::getId` (assuming the the class of `x` and that `getId` is a method of it (typo in posted code?)) – user85421 Feb 13 '20 at 06:46

2 Answers2

7

Collections.emptyList() is a static method that returns a List<T>, i.e. the expression Collections.emptyList() will execute the emptyList() method and its value would be a List<T>. Therefore, you can only pass that expression to methods that require a List argument.

Collections::emptyList is a method reference, which can implement a functional interface whose single method has a matching signature.

A Supplier<List<T>> is a functional interface having a single method that returns a List<T>, which matches the signature of Collections.emptyList(). Therefore, a method - such as Optional's orElseGet(Supplier<? extends T> other) - that in your example requires a Supplier<? extends List<Student>> - can accept the method reference Collections::emptyList, which can implement that interface.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

:: operator is shorthand for lambdas calling a specific method– by name. It is of course even more readable syntax.

It Can be used with static of instance method as well.

for static: Collections::emptyList

for instance : System.out::print

Rahul Anand
  • 165
  • 7