Java – how do I use null’s to sort a collection and then reverse the list?
So I'm using a list of dates, some of which are "" or null I used the answer how to handle nuts 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()); }
Sort the list in ascending order, with null values first
What I want is to have empty values in ascending order, and then sort the values in ascending order according to the above code Then select descending order to flip the list word by word The first ie value in the list is in descending order, followed by all null values
After sorting the list in ascending order, I tried the following: collections reverSEOrder(); This first leaves blank values and then sorts the dates in descending order
I also tried collections reverse(List). This places null values at the end of the list, but keeps the dates in ascending order
Solution
You can do this through a simple comparator and modify it according to your custom bean object
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); } }