سؤال

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.

هل كانت مفيدة؟

المحلول

Use java.lang.Comparator interface.

public class EventComparator implements Comparator<Event> {

    private String tagName;

    public EventComparator(String tagName) {
        this.tagName = tagName;
    }

    @Override
    public int compare(Event e1, Event e2) {
        Tag t1 = getTag(e1, tagName); // getTag(...) returns the e1's tag with name 'tagName'
        Tag t2 = getTag(e2, tagName);

        // Ignoring null check for brevity
        if (t1.getRank() > t2.getRank())
            return 1;
        else if (t1.getRank() < t2.getRank())
            return -1;
        else
            return 0;
    }
}

Usage:

Collections.sort(eventsList, new EventComparator("web"));
Collections.sort(eventsList, new EventComparator("mobile"));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top