0

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

3
  • 3
    So if one of the objects is null, you say they are equal? Commented Apr 28, 2017 at 20:15
  • 1
    What is the output you get, and what is the output you want? Consider creating a Minimal, Complete, and Verifiable example. Commented Apr 28, 2017 at 20:18
  • By the way - Comparator.comparing(AttEnt::getEndTime) is I believe better than writing a custom comparator. It compares the values based on the natural ordering of the type extracted using the passed method reference. Commented Apr 28, 2017 at 20:24

1 Answer 1

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

Java static methods in interfaces are your friend

Click HERE for more awesomeness

Sign up to request clarification or add additional context in comments.

5 Comments

Make sure your AttEnt.getEndTime does not return null
My bad Comparator<AttEnt> comparator = Comparator.reverseOrder().thenComparing(AttEnt::getEndTime)
How about this time Comparator<AttEnt> comparator = Comparator.reverseOrder().thenComparing(Comparator.comparing(AttEnt::getEndTime)) Sorry, I haven't used the other methods for along time, so quite forget their API docs. But this time it should work
Still doesn't like that line.
I tried this also, and it doesn't work either Collections.sort(attempts, (a1, a2) -> a1.getEndTime().compareTo(a2.getEndTime()));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.