0

How do I sort Object arraylist based on timing in the object. for example, 13:00pm to be first second to be 14:00pm and so on if my timing is in an arraylist ? So basically Object with timing of 13:00PM will be sort to first position and object with timing of 14:00 PM will be sort to second position in the object arraylist

Below is my object:

arraylist
ordersArrayList.add(new Orders(AN,collectionTime,name,Integer.parseInt(quantity),tid,addOn));

Collection Time values are like 13:00 PM and 14:00 PM and so on.

I tried using Collection sort but not really sure how to use it with Object

Zoe
  • 27,060
  • 21
  • 118
  • 148
Justin
  • 63
  • 1
  • 1
  • 7
  • In Java, you can use a lambda expression to sort an `ArrayList` as described [here](https://stackoverflow.com/questions/21970719/java-arrays-sort-with-lambda-expression). I don't know if there is any specific behavior in Android – Matthias Beaupère Jun 04 '19 at 12:16

2 Answers2

1

You can sort the objects in Lists using Anonymous Comparator. You can sort the List using Anonymous Comparator as follows:

List<String> listOfTime = new ArrayList<String>();
l.add("10:00 pm");
l.add("4:32 am");
l.add("9:10 am");
l.add("7:00 pm");
l.add("1:00 am");
l.add("2:00 am");
Collections.sort(listOfTime, new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        try {
            return new SimpleDateFormat("hh:mm a").parse(o1).compareTo(new SimpleDateFormat("hh:mm a").parse(o2));
        } catch (ParseException e) {
            return 0;
        }
        }
    });
}

This solution is available at Sort ArrayList with times in Java.

Vedprakash Wagh
  • 3,595
  • 3
  • 12
  • 33
0

Try this one

List<String> l = new ArrayList<String>();
l.add("08:00");
l.add("08:32");
l.add("08:10");
l.add("13:00");
l.add("15:00");
l.add("14:00");
Collections.sort(l, new Comparator<String>() {

@Override
public int compare(String o1, String o2) {
    try {
        return new SimpleDateFormat("HH:mm a").parse(o1).compareTo(new SimpleDateFormat("HH:mm a").parse(o2));
    } catch (ParseException e) {
        return 0;
    }
    }
});
System.out.println(l);
Sanwal Singh
  • 1,765
  • 3
  • 17
  • 35