Reputation: 375
I am building a android project where am storing some details which includes date as string,but now I need to sort the list view by date.I am bit confused on how to do it.I am done with everything but need to sort the list by date.
Here is the overview of how am storing data.
I have an arraylist of type Person like
ArrayList<Person> personDetails = new ArrayList<Person>();
Person class consists of several variable but I will limit to three 1)name 2)Record created(date) 3)Address
then add to Person like personDetails.add(Person Object).
Please guide me on how to sort the list by date.
Thanks for your time.
Upvotes: 2
Views: 8028
Reputation: 347
Or do something like that if you don't want to implements Comparable interface in your Person class:
List<Personne> personDetails = new ArrayList<Personne>();
Collections.sort(personDetails, new Comparator<Personne>()
{
public int compare(Person o1, Person o2) {
SimpleDateFormat sdf = new SimpleDateFormat("YOUR-DATE-PATTERN");
Date d1 = sdf.parse(o1.getDateAsString());
Date d2 = sdf.parse(o2.getDateAsString());
return d1.compareTo(d2);
}
});
Upvotes: 3
Reputation: 888
Implement Comparable
in your Person
class:
public class Person implements Comparable<Person> {
public int compareTo(Person person) {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
return sdf.parse(this.dateString).compareTo(sdf.parse(person.dateString));
}
}
Replace "YYYY-MM-dd"
with the format of your date string.
Upvotes: 2
Reputation: 2037
You can implement Comparable
in your class Person
, and define the order in the compareTo
method.
public class Person implements Comparable<Person>{
public int compareTo(Person comparePerson) {
//logic here
}
}
Then just call:
Collections.sort(personDetails);
Good tutorial: http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
Upvotes: 1