3 回答
TA贡献1966条经验 获得超4个赞
您可以进一步专门化 compareTo 函数以进行二次比较。我假设每个列表至少包含一个国家;如果不是这种情况,您必须处理空列表。改变后的 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贡献1796条经验 获得超10个赞
如果你这样做,接受的答案建议:
wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed()
.thenComparing(wonder -> wonder.getCountries().get(0)));
在您提供的文本文件上,您将获得下一个结果:
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。顺序不一样。不知道这是否与您有关。
PS 如果你实施Comparable#compareTo(),你也应该实施,equals()因为它们之间有合同:
(x.compareTo(y) == 0) == (x.equals(y))
如果不是这种情况,您应该注意:This class has a natural ordering that is inconsistent with equals.
最后一件事:
compareTo()NullPointerException如果当前对象与对象进行比较,null而不是在这种情况下equals()返回,则必须抛出。false
TA贡献1877条经验 获得超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;
}
}
添加回答
举报