sort 及 Comparator

Java中的使用Comparator进行排序的sort方法

  • 当a,b 比较返回大于等于0时, a,b位置不变
  • 当a,b比较返回结果小于0时,a,b交互位置
  • 当使用compareTo时,大于返回 1,小于返回 -1 ,相当于升序排列
  • 总结:若 a > b 返回正数及0为升序,返回负数为降序。
List<Long> list = CollectionUtil.newArrayList(3L, 5L, 1L, 9L);
Collections.sort(list, (a, b) -> a - b > 0 ? 1 : -1);
log.info(JsonUtils.toJson(list));
// [1,3,5,9]
Collections.sort(list, (a, b) -> a - b > 0 ? 0 : -1); // [1,3,5,9]
Collections.sort(list, (a, b) -> a - b > 0 ? -1 : 1); // [9,5,3,1]
Collections.sort(list, (a, b) -> a - b > 0 ? -1 : 0); // [9,5,3,1]
Collections.sort(list, (a, b) -> a - b > 0 ? 1 : 0); // [3,5,1,9]
Collections.sort(list, (a, b) -> a.compareTo(b)); // [1,3,5,9]
原文地址:https://www.cnblogs.com/syui-terra/p/14078533.html