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".
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With