Reputation: 63
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
Upvotes: 0
Views: 166
Reputation: 3712
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.
Upvotes: 1
Reputation: 1793
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);
Upvotes: 0