Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a list of different type of objects

Tags:

java

I have a list of objects which contains different types of objects but a single property is common among all. list contains objects of Field class, Button Class, Page class etc but one property is common among all i.e. "sequence_no" & I want to sort this list on the basis of "sequence_no".

like image 826
SOP Avatar asked Mar 14 '23 18:03

SOP


1 Answers

I'd suggest creating an interface, something like "Sequenceable" with a method getSequenceNo().

public interface Sequenceable {
    int getSequenceNo();
}

Your Field, Button, Page classes should implement this interface and the getSequenceNo() method will return your sequence_no.

Then you can implement your own Comparator and sort using this comparator.

For example, your comparator will look like:

class MyComparator implements Comparator<Sequenceable> {

    @Override
    public int compare(Sequenceable o1, Sequenceable o2) {
        return o2.getSequenceNo() - o1.getSequenceNo();
    }
}

Then you can sort with:

Collections.sort(list, new MyComparator());
like image 104
Amila Avatar answered Mar 25 '23 03:03

Amila