I have two objects which have the following structure:
public class Event{
private String name;
private int id;
private List<Tags> tags;
}
public class Tags{
private String tagName;
private int rank;
}
I have a list of Event objects
List<Event> events = new ArrayList<Event>();
I want to sort the events based on the rank in the Tags object.
For Example,
Tags tag1 = new Tags("web", 1);
Tags tag2 = new Tags("mobile", 7);
List<Tags> tags = new ArrayList<Tags>();
tags.add(tag1);
tags.add(tag2);
Event event1 = new Event("test1",4242432, tags);
Tags tag3 = new Tags("web", 2);
Tags tag4 = new Tags("mobile", 8);
List<Tags> tags1 = new ArrayList<Tags>();
tags.add(tag3);
tags.add(tag4);
Event event2 = new Event("test2",546423, tags1);
So now I want to sort these two events based on the rank field within the Tags object. Since Tags is an ArrayList there can be multiple ranks, so I want to pass an argument, tagName, which will decide which ranks to compare within different Tags objects.
Comparatorinterface is for. Implement aComparator<Event>that returns -1, 0 or 1 when comparing twoEventobjects. However, you have to decide what you mean by "based on the rank field within theTagsobject". EachEventcontains potentially more than oneTagsobject. Also, we're not going to write it for you. Post what you have written so far.Eventobjects based on sometagName"? and not "How to sort list ofEvent?...... To perform any kind of sort, you should first have a way to compare two similar objects. Which sorting algo to use is a next question.