fork(1) download
  1. import java.util.Arrays;
  2. import java.util.Comparator;
  3.  
  4. class SortByComparator
  5. {
  6. static class Item{
  7. String name;
  8. int birth;
  9. Item(String n, int b){
  10. name = n;
  11. birth = b;
  12. }
  13. public String toString(){
  14. return "["+name+", "+birth+"]";
  15. }
  16. }
  17.  
  18. public static void main (String[] args) throws java.lang.Exception
  19. {
  20. Item chopin = new Item("Chopin", 1810);
  21. Item mozart = new Item("Mozart", 1756);
  22. Item beethoven = new Item("Beethoven", 1770);
  23. Item[] items = new Item[]{chopin, mozart, beethoven};
  24.  
  25. Comparator<Item> c = new Comparator<Item>(){
  26. public int compare(Item a, Item b){
  27. return a.birth - b.birth;
  28. }
  29. };
  30.  
  31. Arrays.sort(items, c);
  32.  
  33. for(Item it:items)
  34. System.out.println(it);
  35. }
  36. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
[Mozart, 1756]
[Beethoven, 1770]
[Chopin, 1810]