有一个需求是要对拼接出来的飞行线路列表进行排序,自然地用到Collections.sort方法,然后实现自己的Comparator。
排序需要考虑多种因素,包括拼接出的线路的段数、线路经过的国家数等,其中有一个排序条件是:当线路的飞行时长大于待比较线路飞行时长的1.5倍时,忽略该线路在段数和国家数上的优势。
代码实现如下:
Collections.sort(results, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
...
//若线路的飞行时长大于待比较线路飞行时长的1.5倍,则不再比较其他排序因素
if(consumeTime1 > 1.5 * consumeTime2){
return 1;
}
//段数越少,排序越靠前
if(sectionNum1 > sectionNum2) return 1;
if(sectionNum1 < sectionNum2) return -1;
...
}
貌似看起来没有什么问题,但偶然发现,有些排序不符合预期,细想后发现,以上排序规则其实是违背对称性的。
if(consumeTime1 > 1.5 * consumeTime2)
这个条件在consumeTime1 > consumeTime2的情况下是符合预期的,但当把比较的两个对象掉转过来,排序规则却不是对称的,即可能出现o1 > o2,o2 !<(不小于) o1的情况。
修改代码如下:
Collections.sort(results, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
...
//若线路的飞行时长小于待比较线路,并且乘以1.5倍后仍小于,则不再比较其他排序因素
if(consumeTime1 < consumeTime2 && 1.5 * consumeTime1 < consumeTime2){
return -1;
}
//若线路的飞行时长大于待比较线路,且超过其飞行时长的1.5倍,则不再比较其他排序因素
if(consumeTime1 > consumeTime2 && consumeTime1 > 1.5 * consumeTime2){
return 1;
}
//段数越少,排序越靠前
if(sectionNum1 > sectionNum2) return 1;
if(sectionNum1 < sectionNum2) return -1;
...
}
问题解决。
分享到:
相关推荐
NULL 博文链接:https://xuedong.iteye.com/blog/1147254
APress - Java Collections
Java Collections.pdf 作者john zukowski
主要介绍了Java Collections.sort()实现List排序的默认方法和自定义方法,需要的朋友可以参考下
Java Collections中的Fail Fast机制
Apress的书。很不错,讲的很条理、很简单,是一本完完全全介绍Java Collections API的书籍,其中还有扩展API的例子。总之,真绝对是学习Java数据结构的好书!!!
主要介绍了java中Collections.sort排序详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Comparator是个接口,可重写compare()及equals()这两个方法,接下来通过本文给大家介绍Java中Collections.sort排序,需要的的朋友参考下吧
Java Generics and Collections
Java Collections Apress This book describes how to use this Collections Framework. We'll also look at some of the common alternate frameworks available.
关于 Java Collections API 您不知道的 5 件事
Collins W (2004). Data Structures and the Java Collections Framework..pdf
Java Generics and Collections
很详细的java collection 讲解,希望能够帮助大家.。。。。。
Data Structures and the Java Collections Framework(3rd) 英文无水印pdf 第3版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源...
有关java的collection的学习与应用,这课件挺不错的,欢迎下载。。
译自《Data Structures and the Java Collections Framework》,之前在同平台的其他用户下载的这本书,竟然索要积分50。遂感不平,特再次共享这个资源。
java 使用Collections类对List的排序操作 java 使用Collections类对List的排序操作