I have a task to play with Java Collections framework. I need to obtain a users list from a database, and store it in a collection. (This is finished and users are stored in a HashSet). Each user is an instance of Person class described with name, surname, birth date, join date, and some other parameters which are not important now. Next I need to store the list in different collections (there’s nowhere stated how many) providing functionality to sort them by:
– name only
– name, surname, birthdate
– join date
Ok, so to start with, my Person stores data as Strings only (should I change dates to Date ?). I’ve started implementing sorting with “by name, surname, birthdate”, cause that’s what I get after calling sort on list with Strings. Am I right ?
public List createListByName(Set set){
List ret = new ArrayList<String>();
String data = "";
for(Object p: set){
data = p + "\n";
ret.add(data);
}
Collections.sort(ret);
return ret;
}
But what with the rest ? Here’s my Person :
class Person {
private String firstname;
private String lastname;
)..)
Person(String name, String surname, (..)){
firstname = name;
lastname = surname;
(..)
}
@Override
public String toString(){
return firstname + " " + lastname + " " + (..);
}
}
I wouldn’t convert everything to strings to start with. I would implement
Comparator<Person>and then sort aList<Person>:The
NameSurnameBirthComparatorwould implementComparator<Person>and compare two people by first comparing their first names, then their surnames (if their first names are equal) then their birth dates (if their surnames are equal).Something like this:
And yes, I would store the date of birth as a
Date– or preferably as aLocalDatefrom JodaTime, as that’s a much nicer library for date and time manipulation 🙂