Ok this is a tricky one. I have a list of Sets. I would like to sort the objects in the Sets in an order.
Imagine each set as repressenting a class in a school. Each set contains person objects. A person object holds a String value for name. I'd like to arrange the Persons in the Set by name before I loop through and write them out.
Is there anywahy to use Collections.sort();
or something similar to achieve this?
for (Set<Person> s : listOfAllChildren) {
for (Person p : s) {
if(p.getClass().equalsIgnoreCase("Jones")){
System.out.println(p.getName());
}
else if...//carry on through other classes
}
}
I do know that 2+ children in a class may share the same name but please ignore this
You must implement
Comparable
for your sortable objects (Person
etc).Then:
Set
Collections.sort
or
Examples:
You may want to look at using a
SortedSet
for example aTreeSet
. This allows you to provide aComparator
which in your case can compare the name of thePerson
.You can consider using TreeSet to store objects. And when sorting create new TreeSet with custom comparator for your Person objects. I do not suggest using Collection.sort because AFAIR it can sort only lists.
You could make your Person class implement the Comparable interface as shown here and then sort them accordingly.
With Java 8 you can sort the
Set
of persons and generateList
of persons which are sorted as follows.A
Set
has no notion of ordering because, well, it's a set.There is a
SortedSet
interface implemented byTreeSet
class that you can use. Simply provide an appropriateComparator
to the constructor, or let yourPerson
class implementsComparable
.