-4
List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName)).collect(Collectors.toList());

//working 

while

List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal.getName()).collect(Collectors.toList());

//Not working..

Can any one tell me why i cant use comparator comparing without Method Reference ?

AConsumer
  • 2,461
  • 2
  • 25
  • 33
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Pratibha Jan 27 '18 at 04:43

2 Answers2

6

Comparator#comparing

Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key.

Animal::getName gives the method reference whereas Animal.getName() give you a String (probably).

Reference :

:: (double colon) operator in Java 8

Ravi
  • 30,829
  • 42
  • 119
  • 173
4

It's probably not compiling unless getName() is a static method.

If you don't want to use a method reference (it's not syntatic sugar) use a lambda this should also work.

animals.stream().sorted(Comparator.comparing(a -> a.getName()).collect(Collectors.toList());
dkatzel
  • 31,188
  • 3
  • 63
  • 67