InternalComparator.java 945 B

1234567891011121314151617181920212223242526
  1. List<Country> europe = new ArrayList<Country>();
  2. europe.add(new Country(81903000,357121.41,"Germany"));
  3. europe.add(new Country(64667000,668763, "France"));
  4. europe.add(new Country( 4985900,385199, "Norway"));
  5. europe.add(new Country( 9514406,450295, "Sweden"));
  6. europe.add(new Country(47212990,504645, "Spain"));
  7. europe.add(new Country( 8014000, 41285, "Switzerland"));
  8. europe.add(new Country( 36371, 2.02, "Monaco"));
  9. Collections.sort(europe, new Comparator<Country>(){
  10. @Override
  11. public int compare(Country o1, Country o2) {
  12. double o1Density = o1.population / o1.area;
  13. double o2Density = o2.population / o2.area;
  14. if (Math.abs(o1Density - o2Density) < 0.00001) {
  15. return 0;
  16. } else if (o1Density > o2Density) {
  17. return 1;
  18. } else {
  19. return -1;
  20. }
  21. }
  22. });
  23. // Now it's sorted according to the logic in the internal comparator
  24. System.out.println(europe);