ralyn
ralyn

Reputation: 53

Java Collection sort

I am trying to sort a list of Dates and it's not working.

Here is the declaration and get function in AttEnt

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "end_time")
private Date endTime;

public Date getEndTime() {
    return endTime;
}

Here is the sorting code that isn't doing anything. GetAttempts() gets the list of all the attempts for called. They aren't in order, and I just want to be able to get whatever attempt has the latest endTime.

            List<AttEnt> attempts = called.getAttempts();
            Collections.sort(attempts, new Comparator<AttEnt>() {
            @Override
            public int compare(AttEnt a1, AttEnt a2) {
                if (a1.getEndTime() == null || a2.getEndTime() == null)
                    return 0;
                return a1.getEndTime().compareTo(a2.getEndTime());
                }
            });

I believe that the code above should sort attempts, and then after it attempts should be sorted, so the latest end time would be attempts.get(attempts.size()-1).getEndTime()

Upvotes: 0

Views: 73

Answers (1)

Trash Can
Trash Can

Reputation: 6814

Comparator<AttEnt> comparator = Comparator.comparing(AttEnt::getEndTime).reversed();
attempts.sort(comparator);

Java static methods in interfaces are your friend

Click HERE for more awesomeness

Upvotes: 1

Related Questions