1

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.

piks
  • 1,621
  • 8
  • 32
  • 59

4 Answers4

1

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.

djavaphp
  • 68
  • 7
  • Dint get exactly how does it solve my problem,I just want my custom object to be sorted based on date from latest to oldest in the list.Please provide me the example with sorted list based on date. – piks Jan 06 '14 at 10:13
  • @piks that's the last sentence in the answer - you use `Collections.sort` passing it your list and an instance of your comparator. – Ian Roberts Jan 06 '14 at 10:15
0

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/

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • In case the links go ever black may be add an excerpt of the link directly in your answer? – rene Jan 06 '14 at 10:56
0

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

See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

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());
        }
    });
Laurent
  • 469
  • 3
  • 7