3 回答

TA貢獻(xiàn)1966條經(jīng)驗 獲得超4個贊
您可以進(jìn)一步專門化 compareTo 函數(shù)以進(jìn)行二次比較。我假設(shè)每個列表至少包含一個國家;如果不是這種情況,您必須處理空列表。改變后的 compareTo 是這樣的:
@Override
public int compareTo(Wonder other) {
? ? if(this == other) {
? ? ? ? return 0;
? ? } else if(hostility < other.hostility) {
? ? ? ? return -1;
? ? } else if(hostility > other.hostility) {
? ? ? ? return 1;
? ? } else {
? ? ? ? return -countries.get(0).compareTo(other.countries.get(0));
? ? }
}
或者你可能正在尋找這個:
wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed()
? ? .thenComparing(wonder -> wonder.getCountries().get(0)));
//don't reverse afterwards!

TA貢獻(xiàn)1796條經(jīng)驗 獲得超10個贊
如果你這樣做,接受的答案建議:
wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed()
.thenComparing(wonder -> wonder.getCountries().get(0)));
在您提供的文本文件上,您將獲得下一個結(jié)果:
95 [Antarctica]
95 [Italy]
95 [Tibet, Nepal]
91 [Israel, Jordan]
85 [France, Italy, Switzerland]
85 [Italy, France]
84 [African Union]
84 [Mongolia, China]
82 [Argentina]
80 [USA]
70 [Australia]
69 [Japan]
69 [USA, Canada]
65 [The Hawaiian Islands]
65 [USA]
55 [Russia]
50 [Brazil, Argentina]
19 [Tanzania]
17 [Northern Ireland]
16 [China]
12 [African Union]
10 [Australia]
10 [Brazil]
2 [USA]
但是,如果您先排序countries然后接受答案:
wonders.forEach(wonder -> Collections.sort(wonder.getCountries()));
wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed().
thenComparing(wonder -> wonder.getCountries().get(0)));
然后你會得到:
95 [Antarctica]
95 [Italy]
95 [Nepal, Tibet]
91 [Israel, Jordan]
85 [France, Italy]
85 [France, Italy, Switzerland]
84 [African Union]
84 [China, Mongolia]
82 [Argentina]
80 [USA]
70 [Australia]
69 [Canada, USA]
69 [Japan]
65 [The Hawaiian Islands]
65 [USA]
55 [Russia]
50 [Argentina, Brazil]
19 [Tanzania]
17 [Northern Ireland]
16 [China]
12 [African Union]
10 [Australia]
10 [Brazil]
2 [USA]
注意這兩個列表中的hostility值85和值69。順序不一樣。不知道這是否與您有關(guān)。
PS 如果你實(shí)施Comparable#compareTo(),你也應(yīng)該實(shí)施,equals()因為它們之間有合同:
(x.compareTo(y) == 0) == (x.equals(y))
如果不是這種情況,您應(yīng)該注意:This class has a natural ordering that is inconsistent with equals.
最后一件事:
compareTo()NullPointerException如果當(dāng)前對象與對象進(jìn)行比較,null而不是在這種情況下equals()返回,則必須拋出。false

TA貢獻(xiàn)1877條經(jīng)驗 獲得超1個贊
不確定我明白你的問題是什么。下面的偽代碼能解決您的問題嗎?
@Override
public int compareTo(Wonder other) {
if(hostility == other.hostility) {
// let's compare the strings list when hostility integer are equals (84, 84)
String firstOtherCountry = other.countries.SortAlphabetically().get(0);
// we sort the countries list for current line and other wonder
// you compare alphabetically first element of each list :
// return 1, 0 or -1 here.
} else if(hostility < other.hostility) {
return -1;
} else if(hostility > other.hostility) {
return 1;
} else {
return 0;
}
}
添加回答
舉報