Reputation: 97
I have 2 array lists. One is an array list containing birthdays. The other is an array list of names.
I am sorting the array list of dates in descending order by date using
Collections.sort(birthdayList);
I want to have the array list of names be sorted in the same order that the birthday list was.
i.e.
unsorted
bdaylist namelist
1/20/1980 - Bob
3/15/1970 - Todd
8/25/1990 - Jeff
becomes
sorted
3/15/1970 - Todd
1/20/1980 - Bob
8/25/1990 - Jeff
What would be the most efficient way to do this in Java?
Thank you very much!
Upvotes: 0
Views: 2576
Reputation: 11946
The other answers about implementing Comparable
and using it as the comparator are all indeed correct. But, if this also helps...
According to the Javadoc for Collections.sort, it is noted that sort() uses Modified Mergesort as the sorting algorithm. Correct me if I am wrong, but it is widely accepted that Merge Sort achieves the best possible running time for the worst-case scenario out of all sorting algorithms out there: O(n log n) (I'm not eliminating the fact that there may be other sort algorithms that also achieve O(n log n) in the worst case).
But, O(n log n) is only the best possible run time for an unbounded domain of values. If you have a bound on your domain, then you can get an even better runtime of O(n) using Bucket Sort.
Upvotes: 0
Reputation: 23413
Create a class like this:
public class Person implements Comparable<Person> {
private String name;
private Date date;
public Person(String name, Date date) {
this.name = name;
this.date = date;
}
public String getName() {
return name;
}
public Date getDate() {
return date;
}
@Override
public int compareTo(Person o) {
return this.date.compareTo(o.getDate());
}
}
Then you can sort the list of Person
objects like this:
public static void main(String... args) {
LinkedList<Person> persons = new LinkedList<Person>();
persons.add(new Person("Name1", new Date())); //Specify different dates
persons.add(new Person("Name2", new Date()));
persons.add(new Person("Name3", new Date()));
Collections.sort(persons);
//Collections.sort(persons, Collections.reverseOrder()); //Reverse order
}
That's it.
Or another alternative is to use Comparator
:
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
Reverse order:
Collections.sort(persons, Collections.reverseOrder(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getDate().compareTo(o2.getDate());
}
}));
Then you don't need to implement Comparable<Person>
in your person class.
Upvotes: 4
Reputation: 328923
Upvotes: 8
Reputation: 198481
Don't sort two array lists; sort one array list filled with combined objects containing both the date and the name. That's really the only way.
Upvotes: 3