最近某个需求有个特点,集合中存在各种状态的元素,这些元素按照正常流程展示时直接倒序展示即可,但遇到特殊情况,某个元素需展示在最前。
倒序处理
指定元素在最前
List<Integer> numbers = Lists.newArrayList(70, 30, 0, 40);
System.out.println(numbers);
numbers.sort(((o1, o2) -> {
if (o1 == 0) {
return -1;
}
return o2.compareTo(o1);
}));
System.out.println(numbers);
排序前输出:[70, 30, 0, 40]
排序后输出:[0, 70, 40, 30]
指定元素在最后
List<Integer> numbers = Lists.newArrayList(70, 30, 0, 40);
System.out.println("排序前输出:" + numbers);
numbers.sort(((o1, o2) -> {
if (o1 == 0) {
return 1;
}
return o2.compareTo(o1);
}));
System.out.println("排序后输出:" + numbers);
排序前输出:[70, 30, 0, 40]
排序后输出:[70, 40, 30, 0]
正序处理
指定元素在最前
List<Integer> numbers = Lists.newArrayList(70, 30, 0, 40);
System.out.println("排序前输出:" + numbers);
numbers.sort(((o1, o2) -> {
if (o1 == 0) {
return -1;
}
return o1.compareTo(o2);
}));
System.out.println("排序后输出:" + numbers);
排序前输出:[70, 40, 30, 0]
排序后输出:[0, 30, 40, 70]
指定元素在最后
List<Integer> numbers = Lists.newArrayList(70, 30, 0, 40);
System.out.println("排序前输出:" + numbers);
numbers.sort(((o1, o2) -> {
if (o1 == 0) {
return 1;
}
return o1.compareTo(o2);
}));
System.out.println("排序后输出:" + numbers);
排序前输出:[70, 40, 30, 0]
排序后输出:[30, 40, 70, 0]
标签:30,40,最前,numbers,70,集合,排序,o1
From: https://www.cnblogs.com/zhengyulun/p/17136665.html