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