0

I am adding a feature in my app which lets the user fill entries for past dates, if today is 14/03/2020 then it lets you fill entries for 10/03/2020(or any other date). But I am Having a problem with sorting my arraylist such that all the entries with same dates are together in the arraylist.

I show the entries to the user in a custom ListView and so to make my app user friendly I want to make all those entries with the same date to appear together.

I have a custom arraylist which accepts a Expense Name(String),Amount(String) and Date(String)

ArrayList<ExpenseData> customArrayList=new ArrayList<ExpenseData>();

If you need any other information please ask... Thank You!

Xen
  • 89
  • 1
  • 8

3 Answers3

2

You can use below method to sort your list by date.

 Collections.sort(list, (item1, item2) -> {
            Date date1 = stringToDate(item1.getDate());
            Date date2 = stringToDate(item2.getDate());

            if (date1 != null && date2 != null) {
                boolean b1;
                boolean b2;
                if (isAscending) {
                    b1 = date2.after(date1);
                    b2 = date2.before(date1);
                }else {
                    b1 = date1.after(date2);
                    b2 = date1.before(date2);
                }

                if (b1 != b2) {
                    if (b1) {
                        return -1;
                    }
                    if (!b1) {
                        return 1;
                    }
                }
            }
            return 0;
        });

public static Date stringToDate(String strDate) {
        if (strDate == null)
            return null;

        // change the date format whatever you have used in your model class.
        SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
        Date date = null;
        try {
            date = format.parse(strDate);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
DB377
  • 403
  • 4
  • 11
1

It is very bad practice to directly store Date or Time as String.

Instead you have store the Date or Time as Epoch value (Integer). That way you will have a lot of flexibility while displaying as well as Sorting or other operations.

And you can sort it in Increasing order for Old to New, Decreasing order for New to Old.

Hope it helps

Susheel Karam
  • 837
  • 7
  • 16
0

You can easily sort the data in the required format by using Comparable or Comparator.

Your ExpenseData class which contains the date can implement Comparable interface and override the compareTo() method, where you define the logic to sort the dates.

For complete and detailed tutorial refer below this.

Rajvir
  • 108
  • 7