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 Set has no notion of ordering because, well, it's a set.
There is a SortedSet interface implemented by TreeSet class that you can use. Simply provide an appropriate Comparator to the constructor, or let your Person class implements Comparable.
With Java 8 you can sort the Set of persons and generate List of persons which are sorted as follows.
List<Person> personList = personSet.stream().sorted((e1, e2) ->
e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With