Search code examples
collectionsjava-8java-streamcomparatoricomparable

comparing Instants in Java8


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

Solution

  • 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)