Customized sorting of custom object

user10806781 :

I am trying to sort custom objects on some custom order but I am not able to. I can sort if objects are String or integer. I have posted some detailed description on code below. Thanks for any help.

Private static final List<String> places = Arrays.asList(“Switzerland”, “America”, “Romania”, “Chad”, "Australia"); 
//this list is fixed and always needs to maintain this order

Map<String, String> countrFromDB = countryDAO.getAllCOuntriesFromDB();

List<Country> sortCountry= new ArrayList<>();
for(Map.Entry<String, String> entry : countrFromDB.entrySet() ){
  Country c = new Country(entry.getKey(), entry.getValue());
  sortCountry.add(c);

  if(places.contains(countrFromDB.getKeyValue())){
    sortCountry.add(c.getKeyValue());
  }
}


for(Country data:sortCountry){
System.out.println(data.getKeyValue());
}

I get America, Chad, Australia, Switzerland, Romania. However, I need to maintain order like in

places = Switzerland, America, Romania, Chad, Australia
Dickens A S :

You have to use indexOf in the comparator

final List<String> places = Arrays.asList("Switzerland", "America", "Romania", "Chad", "Australia"); 
.....
.....
.....

Collections.sort(sortCountry, new Comparator<Country>(){
    public int compare(Country o1, Country o2){
        return places.indexOf(o1.getValue()) - places.indexOf(o2.getValue());
    }
});

for(Country data:sortCountry){
    System.out.println(data.getValue());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=372254&siteId=1