How to Sort Date in descending order From Arraylist Date in android?

前端 未结 6 1649
名媛妹妹
名媛妹妹 2020-12-15 21:04

I have an ArrayList which stores Dates and I sorted them in descending order. Now I want to display them in a ListView. This is what I

6条回答
  •  感动是毒
    2020-12-15 21:11

    Date's compareTo() you're using will work for ascending order.

    To do descending, just reverse the value of compareTo() coming out. You can use a single Comparator class that takes in a flag/enum in the constructor that identifies the sort order

    public int compare(MyObject lhs, MyObject rhs) {
    
        if(SortDirection.Ascending == m_sortDirection) {
            return lhs.MyDateTime.compareTo(rhs.MyDateTime);
        }
    
        return rhs.MyDateTime.compareTo(lhs.MyDateTime);
    }
    

    You need to call Collections.sort() to actually sort the list.

    As a side note, I'm not sure why you're defining your map inside your for loop. I'm not exactly sure what your code is trying to do, but I assume you want to populate the indexed values from your for loop in to the map.

提交回复
热议问题