Sort objects in ArrayList by date?

后端 未结 14 2127
生来不讨喜
生来不讨喜 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 06:59

    This is how I solved:

    Collections.sort(MyList, (o1, o2) -> o1.getLastModified().compareTo(o2.getLastModified()));
    

    Hope it help you.

    0 讨论(0)
  • 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<String, String> by one object in the list, that being the timestamp.

    I have these objects:

    ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
    

    The map objects are as follows:

    Map<String, Object> 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<String, String>) firstObjToCompare).get("timestamp");
        String secondDateString = ((HashMap<String, String>) 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 =]

    0 讨论(0)
  • 2020-11-22 07:01

    The Date class already implements Comparator interface. Assuming you have the class below:

    public class A {
    
        private Date dateTime;
    
        public Date getDateTime() {
            return dateTime;
        }
    
        .... other variables
    
    }
    

    And let's say you have a list of A objects as List<A> aList, you can easily sort it with Java 8's stream API (snippet below):

    import java.util.Comparator;
    import java.util.stream.Collectors;
    
    ...
    
    aList = aList.stream()
            .sorted(Comparator.comparing(A::getDateTime))
            .collect(Collectors.toList())
    
    0 讨论(0)
  • 2020-11-22 07:04

    Since Java 8 the List interface provides the sort method. Combined with lambda expression the easiest solution would be

    // sort DateTime typed list
    list.sort((d1,d2) -> d1.compareTo(d2));
    // or an object which has an DateTime attribute
    list.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));
    // or like mentioned by Tunaki
    list.sort(Comparator.comparing(o -> o.getDateTime()));
    

    Reverse sorting

    Java 8 comes also with some handy methods for reverse sorting.

    //requested by lily
    list.sort(Comparator.comparing(o -> o.getDateTime()).reversed());
    
    0 讨论(0)
  • 2020-11-22 07:04

    Here's the answer of how I achieve it:

    Mylist.sort(Comparator.comparing(myClass::getStarttime));
    
    0 讨论(0)
  • 2020-11-22 07:08
    list.sort(Comparator.comparing(o -> o.getDateTime()));
    

    The best answer IMHO from Tunaki using Java 8 lambda

    0 讨论(0)
提交回复
热议问题