Skip to content Skip to sidebar Skip to footer

Android - How To Sort Arraylist By Date?

I'm trying to sort my arrayList by date. I stored the date on Firebase each time I receive a notification and is retrieved from there. I'm using Collections.sort but I don't know h

Solution 1:

Do sorting after parsing the date.

Collections.sort(notificationList, newComparator<Notification>() {
            DateFormatf=newSimpleDateFormat("dd/MM/yyyy '@'hh:mm a");
            @Overridepublicintcompare(Notification lhs, Notification rhs) {
                try {
                    return f.parse(lhs.getDate()).compareTo(f.parse(rhs.getDate()));
                } catch (ParseException e) {
                    thrownewIllegalArgumentException(e);
                }
            }
        })

If your date is in some other format, write the DateFormat accordingly.

Solution 2:

Consider storing the date in Notification as a long (unix time) or a Date (LocalDateTime if you're using Java 8 support) and formatting it as a String only when displaying it to the UI.

Solution 3:

You can simply parse the date-time strings into LocalDateTime and perform a natural sorting.

Using Stream:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;

publicclassMain {
    publicstaticvoidmain(String[] args) {
        finalDateTimeFormatterdtf= DateTimeFormatter.ofPattern("d MMM u 'at' h:m a", Locale.UK);
        
        Stream.of(
                    "10 Jul 2017 at 10:59 pm",
                    "10 Jul 2017 at 10:59 pm",
                    "11 Jul 2017 at 11:15 pm",
                    "9 Jul 2017 at 11:15 pm"
                )
                .map(s -> LocalDateTime.parse(s, dtf))
                .sorted()
                .forEach(dt -> System.out.println(dtf.format(dt)));
    }
}

Output:

9Jul2017 at11:15pm10Jul2017 at10:59pm10Jul2017 at10:59pm11Jul2017 at11:15pm

Non-Stream solution:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

publicclassMain {
    publicstaticvoidmain(String[] args) {
        finalDateTimeFormatterdtf= DateTimeFormatter.ofPattern("d MMM u 'at' h:m a", Locale.UK);
        List<LocalDateTime> listLdt = newArrayList<>();
        
        List<String> listDtStr = 
                Arrays.asList(
                                "10 Jul 2017 at 10:59 pm",
                                "10 Jul 2017 at 10:59 pm",
                                "11 Jul 2017 at 11:15 pm",
                                "9 Jul 2017 at 11:15 pm"
                            );
        
        // Add the strings, parsed into LocalDateTime, to listLdtfor(String s: listDtStr) {
            listLdt.add(LocalDateTime.parse(s, dtf));
        }
        
        // Sort listLdt
        Collections.sort(listLdt);
        
        // Displayfor(LocalDateTime ldt: listLdt) {
            System.out.println(ldt.format(dtf));
        }
    }
}

Output:

9Jul2017 at11:15pm10Jul2017 at10:59pm10Jul2017 at10:59pm11Jul2017 at11:15pm

Learn more about the modern date-time API from Trail: Date Time.

Using legacy date-time API:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

publicclassMain {
    publicstaticvoidmain(String[] args)throws ParseException {
        finalSimpleDateFormatsdf=newSimpleDateFormat("d MMM u 'at' h:m a", Locale.UK);
        List<Date> listDate = newArrayList<>();
        
        List<String> listDtStr = 
                Arrays.asList(
                                "10 Jul 2017 at 10:59 pm",
                                "10 Jul 2017 at 10:59 pm",
                                "11 Jul 2017 at 11:15 pm",
                                "9 Jul 2017 at 11:15 pm"
                            );
        
        // Add the strings, parsed into LocalDateTime, to listDatefor(String s: listDtStr) {
            listDate.add(sdf.parse(s));
        }
        
        // Sort listDate
        Collections.sort(listDate);
        
        // Displayfor(Date date: listDate) {
            System.out.println(sdf.format(date));
        }
    }
}

Output:

9 Jul 4 at 11:15 pm
10 Jul 5 at 10:59 pm
10 Jul 5 at 10:59 pm
11 Jul 6 at 11:15 pm

Note: The java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.


Solution 4:

As I understand, Notification.getDate() returns String value. So, use

publicstatic Date toDate(String value)throws ParseException {
    DateFormatformat=newSimpleDateFormat("d MMMM yyyy 'at' HH:mm'am'", Locale.ENGLISH);
    return format.parse(value);
}

this method to det Date from your String. Just get two dates and use Date.compareTo method.

date1 = toDate(lhs.getDate());
date2 = toDate(rhs.getDate());
date1.compareTo(date2);

Solution 5:

Instead of setting date like following in Notification model.

String notificationTime = currentDateTimeString + " at " + currentTime;

you can save time as System.currentTimeinMillis(); and while displaying then parse it to Date as following

DateFormatf=newSimpleDateFormat("dd/MM/yyyy hh:mm a");
f.parse(timeStamp);

Post a Comment for "Android - How To Sort Arraylist By Date?"