java – 如何使用null’s对集合进行排序并在之后反转列表?
发布时间:2020-12-15 04:26:15 所属栏目:Java 来源:网络整理
导读:所以我正在使用日期列表,其中一些值是“”即null.我用了 How to handle nulls when using Java collection sort的答案 public int compare(MyBean o1,MyBean o2) { if (o1.getDate() == null) { return (o2.getDate() == null) ? 0 : -1; } if (o2.getDate()
所以我正在使用日期列表,其中一些值是“”即null.我用了
How to handle nulls when using Java collection sort的答案
public int compare(MyBean o1,MyBean o2) { if (o1.getDate() == null) { return (o2.getDate() == null) ? 0 : -1; } if (o2.getDate() == null) { return 1; } return o2.getDate().compareTo(o1.getDate()); } 以升序对列表进行排序,将空值放在第一位. 我想要的是按升序顺序首先有空值,然后按照上面的代码按升序排列值.然后选择降序以逐字翻转列表.列表中的IE第一个值按降序排列,然后是所有空值. 我按照升序排序列表后尝试了以下内容:Collections.reverSEOrder(); 我也尝试过Collections.reverse(List).这将空值放在列表的末尾,但保持日期按升序排列. 解决方法
您可以通过一个简单的比较器实现这一目根据您的自定义bean对象修改它.
像这样的东西 – public class DateComparator implements Comparator<Date> { private boolean reverse; public DateComparator(boolean reverse) { this.reverse = reverse; } public int compare(Date o1,Date o2) { if (o1 == null || o2 == null) { return o2 != null ? (reverse ? 1 : -1) : (o1 != null ? (reverse ? -1 : 1) : 0); } int result = o1.compareTo(o2); return reverse ? result * -1 : result; } public static void main(String[] args) throws ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date[] dates = new Date[]{null,dateFormat.parse("10-10-2013"),null,dateFormat.parse("10-10-2012"),dateFormat.parse("10-10-2015"),dateFormat.parse("10-10-2011"),null}; List<Date> list = Arrays.asList(dates); Collections.sort(list,new DateComparator(false)); System.out.println(list); Collections.sort(list,new DateComparator(true)); System.out.println(list); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |