Sourabh Saldi
Sourabh Saldi

Reputation: 3587

using two comparators in java android

I need to sort object list using comparators I need nested type sorting

such as first sort by first property then by second and so on..

I tried something like..

dinerlist = repository.Retrieve();
            ComparatorChain chain = new ComparatorChain();
            chain.addComparator(new TagEntry.SortByUsertype());
            chain.addComparator(new TagEntry.SortByCompany());
            chain.addComparator(new TagEntry.SortByUsername());
            Collections.sort(dinerlist, chain);
            size = dinerlist.size();

the problem that I get here is noclassdefifound for comparatorchain although i've imported the package in my code

also is there any other way to compare objects

Upvotes: 0

Views: 609

Answers (1)

user219882
user219882

Reputation: 15844

You can make this in Java (without Android libraries). I can think of two options right now

  1. write one comparator which compares more fields at once
  2. write more comparators where each one compares only one field

And there are two ways how to compare objects

Comparable interface

public class Foo implements Comparable<Foo> {
    public int compareTo(Foo foo) {
        // compare them
    }
}

Custom comparator - you can pass this to Collections.sort

public class CustomComparator implements Comparator<Foo> {

    public int compare(Foo foo1, Foo foo2) {
        // compare them
    }
}

I would suggest to create more custom comparators and use similar (it's just a raw code) method to process them all

public int compare(Object o1, Object o2) throws UnsupportedOperationException {

    BitSet orderingBits = new BitSet();

    // get iterator for a List of comparators
    Iterator comparators = comparatorList.iterator();
    for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {

        Comparator comparator = (Comparator) comparators.next();
        int retval = comparator.compare(o1,o2);
        if (retval != 0) {
            // invert the order if it is a reverse sort
            if (orderingBits.get(comparatorIndex) == true) {
                retval *= -1;
            }

            return retval;
        }

    }

    // if comparators are exhausted, return 0
    return 0;
}

Source

Upvotes: 1

Related Questions