カスタムオブジェクトの並べ替えのカスタマイズ

user10806781:

私はいくつかのカスタムオーダーにソートカスタムオブジェクトにしようとしていますが、私はすることはできませんよ。オブジェクトは文字列または整数であれば、私は並べ替えることができます。私は以下のコードにいくつかの詳細な説明を掲載しています。任意の助けてくれてありがとう。

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());
}

私が取得しますAmerica, Chad, Australia, Switzerland, Romaniaしかし、私はのように秩序を維持する必要があります

places = Switzerland, America, Romania, Chad, Australia
ディケンズAS:

あなたは使用する必要がindexOfコンパレータに

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());
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=373335&siteId=1