2

I have this object:

public class MatchEvent implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    private Instant dateReceived;

    public Instant getDateReceived() {
        return dateReceived;
    }


    public void setDateReceived(Instant dateReceived) {
        this.dateReceived = dateReceived;
    }

}

that I want to get it ordered by date received;

matchService
            .findAllByDay(today)
                .sorted(Comparator.comparing(MatchEvent::dateReceived))

but is seems that is not possible because I got a compilation error:

Multiple markers at this line
    - The method comparing(Function<? super T,? extends U>) in the type Comparator is not applicable for the arguments 
     (MatchEvent::dateReceived)
    - The type MatchEvent does not define dateReceived(T) that is applicable here
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301
  • 6
    dateReceived is a private field. You need a public `getDateReceived()` **method** in order to use a **method** reference: `Comparator.comparing(MatchEvent::getDateReceived)` – JB Nizet Oct 20 '18 at 06:57

1 Answers1

6

Declare a public method named getDateReceived() inside class MatchEvent as follows:

public Instant getDateReceived(){
    return dateReceived;
}

Then you can use this method as method reference as follows:

Comparator.comparing(MatchEvent::getDateReceived)
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86