Unable to add a logic to sort with dates in the existing comparator in Java/android

余生颓废 提交于 2019-12-06 05:35:32
Neeraj Bagra

First make a function which parse given date

public Date parseDateFromString(String date){
    if(date == null) {
        return null;
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-yy'T'HH:mm:ss", Locale.US);
    try {
        return simpleDateFormat.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
}

and then compare it with Comparator like

if (item1.typeInt != item2.typeInt) {
    return item1.typeInt == MyItemModel.TYPE_MAGAZINE ? 1 : -1;
} else {
    if (parseDateFromString(item1.getStartReading()) == null) {
        return 0;
    } else if (parseDateFromString(item2.getStartReading()) == null) {
        return -1;
    } else {
        return parseDateFromString(item2.getStartReading()).after(parseDateFromString(item1.getStartReading())) ? 1 : -1;
    }
}
public static Comparator<MyItem> myComparator
        // books first; sort by a Boolean expression that is false for books to put them first
        = Comparator.comparing((MyItem it) -> it.type != MyItemModel.TYPE_BOOK)
                // then magazines first
                .thenComparing(it -> it.type != MyItemModel.TYPE_MAGAZINE)
                // then by start date-time, nulls last, otherwise newest first
                .thenComparing(it -> it.startReading,
                        Comparator.nullsLast(Comparator.comparing((String start)
                                -> LocalDateTime.parse(start)).reversed()))
                // then by ID
                .thenComparing(it -> it.id);

Since your API level is high enough for lambdas, I assume that you can also use Comparator.comparing and thenComparing, etc. Do that. It’s not only terser, it is also less error-prone. I suspect that you intended type rather than typeInt in your code, at least it’s not consistent, an inconsistency that you simply cannot make with comparing.

Comparator.nullsLast sorts null values last (there is a sister method nullsFirst in case you want that). Your string of 2018-10-21T13:06:41 is in ISO 8601 format, the format that LocalDateTime parses as its default, that is, without any explicit formatter. We should of course take advantage of this fact. reversed reverses the order of the comparator so the newest rather than the oldest items come first.

EDIT: With inspiration from this answer I am sorting Booleans for getting the books and then magazines first. In the natural ordering of Booleans false comes before true. I sort on it.type != MyItemModel.TYPE_BOOK, which will be false for books, that is, they come first, and true for everything else. Next I do similarly for magazines.

Further possible improvements

  • Declare getters for your attributes and use MyItem::getId rather than it -> it.id.
  • Store startReading as a LocalDateTime rather than a string inside your MyItem, so you don’t need to parse for each comparison (there are many other reasons why this is a good idea). Just format it into a String when you need to present it to the user.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!