Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an java.util.ArrayList<ParentType> based on ChildType?

public interface Human<T> extends Comparable<T>{ }

public class Men implements Human<Men>{
  public Men(String firstName) {
    this.firstName = firstName;
  }
.....
}

public class Women implements Human<Women>{
 public Women(String firstName) {
    this.firstName = firstName;
  }
.....
}

public class MainTest{

   public static void main(String[] args) {

      List<Human> engineers= new ArrayList<Human>();
        engineers.add(new Men("A")); 
            engineers.add(new Women("A"));
        engineers.add(new Men("C"));
        engineers.add(new Men("E"));
        engineers.add(new Men("Z"));
            engineers.add(new Women("J"));
        engineers.add(new Women("B"));
        engineers.add(new Men("X"));
        engineers.add(new Men("O"));
        engineers.add(new Women("G"));   

       Collections.sort(engineers);

       System.out.println(.... print the engineers array...)
}

Output

Men(A); Men(C); Men(E); Men(O); Men(X); Men(Z) Women(A); Women(B); Women(G); Women(AJ);

My sorted the arraylist should to be initially sorted in terms of the TYPE (Men or Women) and the secondary sort is based on firstname. How can I best possibly accomplish this?

I tried the Collections.sort(....)

Couldnt get the desired results.

Thanks in advance

like image 420
Akh Avatar asked Dec 28 '22 13:12

Akh


2 Answers

You probably mean

public interface Human extends Comparable<Human> {}

That is: Human is comparable to other Humans. That being the case, if you want to compare Humans based on type followed by name, then your interface Human needs to express both of those properties:

public interface Human extends Comparable<Human> {
    enum Type { MAN, WOMAN }
    Type getType();
    String getName();
}

Then write an appropriate implementation of compareTo() to take both type and name into account, and use Collections.sort() to sort.

like image 110
Ryan Stewart Avatar answered Dec 30 '22 03:12

Ryan Stewart


You need to use a comparator and Collections.sort(List l, Comparator c)

static final Comparator<Human> MyComparator =
                                 new Comparator<Human>() 
{
    public int compare(Human e1, Human e2) 
    {
            // Your custom comparison code goes here
    }
};

Collections.sort(engineers, MyComparator);

Additional info can be found via the tutorial on object ordering: http://download.oracle.com/javase/tutorial/collections/interfaces/order.html

like image 27
Brian Roach Avatar answered Dec 30 '22 01:12

Brian Roach