Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132939 views
License: OTHER
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
15
if (Math.abs(o1Density - o2Density) < 0.00001) {
16
return 0;
17
} else if (o1Density > o2Density) {
18
return 1;
19
} else {
20
return -1;
21
}
22
}
23
});
24
// Now it's sorted according to the logic in the internal comparator
25
System.out.println(europe);
26
27