fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import static java.util.Comparator.comparing;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. static class Parent{
  12. final String s;
  13. Parent(String s) {this.s=s;}
  14. public String toString() {return s;}
  15. }
  16.  
  17. static class Child1 extends Parent{
  18. Child1(String s) {super(s);}
  19. }
  20.  
  21. static class Child2 extends Parent{
  22. Child2(String s) {super(s);}
  23. }
  24. public static void main (String[] args) throws java.lang.Exception
  25. {
  26. List<Parent> list = Arrays.asList(
  27. new Child1("1a"),
  28. new Child2("2a"),
  29. new Child1("1b"),
  30. new Child2("2b"));
  31.  
  32. List<Class<? extends Parent>> order = Arrays.asList(Child1.class, Child2.class);
  33.  
  34. System.out.println("before " + list);
  35. list.sort(comparing(p -> order.indexOf(p.getClass())));
  36. System.out.println("after " + list);
  37.  
  38.  
  39. }
  40. }
  41.  
Success #stdin #stdout 0.17s 33460KB
stdin
Standard input is empty
stdout
before [1a, 2a, 1b, 2b]
after [1a, 1b, 2a, 2b]