Abhishek Seth Abhishek Seth - 2 months ago 12
Java Question

Sorting ArrayList in n category Java

I have an

ArrayList
of type
ArrayList<Food>
. This
Food
class has two variables
name
and
timing
,
timing
can be
breakfast
,
lunch
and
dinner
. Data coming to
ArrayList
is from a
JSON
which has not sorted it in anyway.


I want to sort this list into 4 categories.


Example:

Rice,breakfast
Hotdog, dinner
carrot shake, breakfast
soup, lunch
chocolate, dinner




TO:




Rice,breakfast
carrot shake, breakfast
soup, lunch
Hotdog, dinner
chocolate, dinner

Answer

You can create a Comparator. Example:

Collections.sort(eventList, new Comparator<Event>() {
        @Override
        public int compare(Event e1, Event e2) {

            return e1.startsOn.compareTo(e2.startsOn);
        }
    });

Where: eventList is an arrayList and the Type of object is Event. You can use the property of your object that you want to compare and that's it.

Best regards.