File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Order a collection by date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Order a collection by date" Watch "Order a collection by date" New topic
Author

Order a collection by date

John Landon
Ranch Hand

Joined: Sep 25, 2008
Posts: 227
Hi,
What is the best way to order a Collection of ClassA by date. The date is stored in ClassA (like new ClassA().date)?

Thanks.
John Landon
Ranch Hand

Joined: Sep 25, 2008
Posts: 227
There is a Collections.public static void sort(List list, Comparator c).
But what do I give it as c?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Originally posted by John Landon:
There is a Collections.public static void sort(List list, Comparator c).
But what do I give it as c?


This is hardly an advanced questio. Perhaps this should be moved to beginners?

Anyway to answer your question. How about something like this?



Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Paul Yule
Ranch Hand

Joined: May 12, 2008
Posts: 229
you need to create a class that implements the comparator...take a look at the comparator interface (2 methods). Or create an anonymous comparator that implements compare() on the spot:
Tom Johnson
Ranch Hand

Joined: May 11, 2005
Posts: 142
Give it a comparator....what else?!! You can use a named implementation or pass an anonymous implementation, as follows:



Hope this helps
[ November 20, 2008: Message edited by: Tom Johnson ]

<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>
John Landon
Ranch Hand

Joined: Sep 25, 2008
Posts: 227
Thanks. Just figured it out.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Order a collection by date