0

Possible Duplicate:
Best way to compare objects by multiple fields?

Hello i'm kinda new to programming and would like to ask help, my teacher created a class wherein the country, continent, and population is given. The desired output is to get the top 10 populated countries for each continent.

Code:

import java.util.*;

public class WP {

public static void main(String[] args) {
    WorldPop[] list = WorldPop.getList();
    int index;

    Arrays.sort(list, new PopComparator());

    for (int i=0; i<list.length; i++) {
        System.out.printf("%-53s %-20s %,14d\n", list[i].country, 
                       list[i].continent, list[i].population);
    }
}
}

class PopComparator implements Comparator<WorldPop> {
public int compare(WorldPop x, WorldPop y) {
    return x.population - y.population;
}
}

class TitleComparator implements Comparator<WorldPop> {
public int compare(WorldPop x, WorldPop y){
    return x.continent.compareTo(y.continent);
}
}
Community
  • 1
  • 1

2 Answers2

3

I'd probably sort each Country into a Map<Continent, List<Country>> by continent, and them simply sort each List

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

First you can sort your list using below Comparator . now your list is sorted based on continental and countries and then iterate them by calculating number of countries for each duplicate continental.

 Collections.sort(list, new Comparator<WorldPop>() {
        @Override
        public int compare(WorldPop x, WorldPop y) {
            int c;
            c = x.continent.compareTo(y.continent);
            if (c == 0)
               c = x.population .compareTo(y.population );
            return c;
        }
    });
amicngh
  • 7,831
  • 3
  • 35
  • 54