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
A
Sethas no notion of ordering because, well, it’s a set.There is a
SortedSetinterface implemented byTreeSetclass that you can use. Simply provide an appropriateComparatorto the constructor, or let yourPersonclass implementsComparable.