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

1
  • In Java, you can use a lambda expression to sort an ArrayList as described here. I don't know if there is any specific behavior in Android Commented Jun 4, 2019 at 12:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But my arraylist is not String but its an object which is ordersArrayList
You can use the same thing above and modify for your own object
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.