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

守給你的承諾、 提交于 2019-12-12 10:13:41

问题


I want to add a condition that also sorts according to the DATE (desc order) of the item.startReading. item.startReading value has the date value in the string format 2018-10-20T12:05:41. But I have no clue how to add this logic to the current code. Before the user clicks the magazine or the book item, the value of item.startReading is null. . When the user clicks the either one of the items, I want the newest item.startReading to go to the top like the following. Sorry for my explanation, but I really need to know how to do since I started learning java/android. Some examples or tips would be lovely. I would love to hear from you.

  1. magazine (2018-10-21T13:06:41) newest date item to go to the top
  2. magazine (2018-10-20T12:05:41)
  3. books
  4. books

Currently, I have the following comparator code that does the sorting like below.

(Before using the comparator)

  1. magazine
  2. books
  3. magazine
  4. books

(After the using the comparator) reoders with type and finally with the ID ↓

  1. books
  2. books
  3. magazine
  4. magazine

My comparator code:

public Comparator<MyItem> myComparator = (item1, item2) -> {
    //How to add the desc date order with Dates?

    if (item1.typeInt == MyItemModel.TYPE_BOOK && item2.typeInt !=  MyItemModel.TYPE_BOOK) {
        return -1;
    } else if (item1.type !=  MyItemModel.TYPE_BOOK && item2.type ==  MyItemModel.TYPE_BOOK) {
        return 1;
    } else if (item1.type == MyItemModel.TYPE_MAGAZINE && item2.type != MyItemModel.TYPE_MAGAZINE) {
        return -1;
    } else if (item1.type != MyItemModel.TYPE_MAGAZINE && item2.type == MyItemModel.TYPE_MAGAZINE) {
        return 1;
    } 
    return (Integer.compare((int) item1.id, (int) item2.id)) * -1;
};

回答1:


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;
    }
}



回答2:


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.


来源:https://stackoverflow.com/questions/52638352/unable-to-add-a-logic-to-sort-with-dates-in-the-existing-comparator-in-java-andr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!