Leave a Comment
源码
list.sorted((o1, o2) -> { return o1.getCreateTime().getTime() - o2.getCreateTime().getTime(); }).limit(limits).collect(Collectors.toList());
但是,此排序算法比老版本的算法多了如下几个限制条件,如果不注意,排序可能会抛异常
1. 自反性,compare(x, y) = – compare(y, x)
2. 传递性,如果compare(x, y) > 0, compare(y, z) > 0, 则必须保证compare(x, z) > 0
3. 对称性, 如果compare(x, y) == 0, 则必须保证compare(x, z) == compare(y, z)
getTime()返回Long导致数据溢出,需要先判断大小再返回1 0 -1
pulledUrls.stream().sorted((o1, o2) -> { if (o1.getCreateTime().getTime() == o2.getCreateTime().getTime()) { return 0; } else { return o1.getCreateTime().getTime() > o2.getCreateTime().getTime() ? 1 : -1; } }).limit(limits).collect(Collectors.toList());