Sort objects in ArrayList by date?

后端 未结 14 2162
生来不讨喜
生来不讨喜 2020-11-22 06:58

Every example I find is about doing this alphabetically, while I need my elements sorted by date.

My ArrayList contains objects on which one of the datamembers is a

14条回答
  •  误落风尘
    2020-11-22 07:01

    This may be an old response but I used some examples from this post to create a comparator that would sort an ArrayList of HashMap by one object in the list, that being the timestamp.

    I have these objects:

    ArrayList> alList = new ArrayList>();
    

    The map objects are as follows:

    Map map = new HashMap<>();
            // of course this is the actual formatted date below in the timestamp
            map.put("timestamp", "MM/dd/yyyy HH:mm:ss"); 
            map.put("item1", "my text goes here");
            map.put("item2", "my text goes here");
    

    That mapping is what I use to load all my objects into the array list, using the alList.add(map) function, within a loop.

    Now, I created my own comparator:

    import org.joda.time.DateTime;
    import org.joda.time.format.DateTimeFormat;
    import org.joda.time.format.DateTimeFormatter;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Map;
    
     public class DateSorter implements Comparator {
         public int compare(Object firstObjToCompare, Object secondObjToCompare) {
        String firstDateString = ((HashMap) firstObjToCompare).get("timestamp");
        String secondDateString = ((HashMap) secondObjToCompare).get("timestamp");
    
        if (secondDateString == null || firstDateString == null) {
            return 0;
        }
    
        // Convert to Dates
        DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
        DateTime firstDate = dtf.parseDateTime(firstDateString);
        DateTime secondDate = dtf.parseDateTime(secondDateString);
    
        if (firstDate.isAfter(secondDate)) return -1;
        else if (firstDate.isBefore(secondDate)) return 1;
        else return 0;
        }
    }
    

    I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.

    Collections.sort(alList, new DateSorter());
    

    This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]

提交回复
热议问题