piks
piks

Reputation: 1673

sort list of custom object contains date from latest to oldest in java

I have custom object contains Date, which I creates dynamically and filled with the data (name, date etc..) and add to the list and after adding all objects into the list I want to sort the list based on the date of custom object (From LATEST to OLDEST). How do I achieve it in Java?

Please provide me the solution with some sample example.

Thanks.

Upvotes: 1

Views: 849

Answers (4)

Laurent
Laurent

Reputation: 519

With null in first position and then from the oldest to the newest :

Collections.sort(myList, new Comparator<MyBean>() {
        public int compare(MyBean b1, MyBean b2) {
            if (b1 == null || b1.getMyDate() == null) {
                return -1;
            }
            if (b2 == null || b2.getMyDate() == null) {
                return 1;
            }
            return b1.getMyDate().compareTo(b2.getMyDate());
        }
    });

Upvotes: 0

djavaphp
djavaphp

Reputation: 68

to Find the difference between 2 dates , you can compare the values. covert dates into Value(long) and than compare rather than using Arithmetic operation like subtraction etc.
public class CompareObjects implements Comparator {

@Override
public int compare(classA c1, classA c2) {
    long value1 = c1.getDate().getTime();
    long value2 = c2.getDate().getTime();
    if (value2 > value1) {
        return 1;
    } else if (value1 > value2) {
        return -1;
    } else {
        return 0;
    }
}

public static void main(String[] args) {
    classA o1 = new classA();
    o1.setDate(new Date());

    classA o2 = new classA();
    o2.setDate(new Date());
    CompareObjects compare = new CompareObjects();
    int i = compare.compare(o1, o2);
    System.out.println(" Result : " + i);

}

}

or without converting you can directly return the result.

return c2.getDate().compareTo(c1.getDate());

after comparison you can use Collection.sort method to set the order.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240860

You could use custom Comparator and then Collections.sort(collection, yourComparatorInstance);

See

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39437

You need to implement a custom Comparator or implement Comparable.

For more details see here.

http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Here are some examples of using either of them.

http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

Upvotes: 0

Related Questions