Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects within a Set by a String value that all objects contain

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

like image 914
Julio Avatar asked Nov 09 '10 09:11

Julio


2 Answers

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.

like image 160
Nicolas Repiquet Avatar answered Oct 04 '22 20:10

Nicolas Repiquet


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());
like image 39
ravthiru Avatar answered Oct 04 '22 20:10

ravthiru