A list of sorting Java objects based on the order of values ​​(e.g. d, s, a, q, c)

I have an arraylist class in the Events class, where the Events class is similar to

class Events {
Date eventDate;
String eventType;
}

Now I want to sort this array first based on the latest eventDate. If two or more events are included on the same date, I will sort them in the following order of event type

1. Maths 2. Science 3. History 4. Algebra.

So if my list

{ "01/01/2010  History", "01/01/2010 Algebra", "01/01/2010 Maths", "01/01/2010 Science"}

Then I want to sort it as

{ "01/01/2010  Maths", "01/01/2010 Science", "01/01/2010 History", "01/01/2010 Algebra"}

Please suggest how can I do this?

TIA, Hanumant.

+3
source share
4 answers

Not tested, but it should give you an idea:

class Events
implements Comparable
{
    Date eventDate;
    String eventType;

    int eventScore()
    {
        if (eventType.equals("Maths"))
            return 0;
        else if (eventType.equals("Science"))
            return 1;
        else if (eventType.equals("History"))
            return 2;
        else if (eventType.equals("Alegbra"))
            return 3;
        return 4;
    }

    public int compareTo(Object o)
    {
        Events other = (Events)o;
        if (other.eventDate.before(this.eventDate))
            return -1;
        else if (other.eventDate.after(this.eventDate))
            return 1;
        return other.eventScore() < this.eventScore() ? -1 : 1;
    }
}
+1
source

You will need to implement Comparator as shown here .

+1
source

. :

class Event implements Comparable {
    private Date date;
    private Event.Type type;

    enum Type {
        MATHS,     // MATH / MATHEMATICS?
        SCIENCE,
        HISTORY,
        ALGEBRA
    }

    public int compareTo(Event other) {
        int comparison = other.date.compareTo(date);
        if (0 == comparison) {
            comparison = type.compareTo(other.type);
        }
        return comparison;
    }
}

a Collection<Event> events Collections.sort(events).

+1

How does this sound like HW, you must implement the Comparable interface for the Events class.

0
source

Source: https://habr.com/ru/post/1789433/


All Articles