Pat
Pat

Reputation: 613

order arraylist based on values

Here is the actual scenario. Have a VO

Name Usagecount  returncount number
A   0       0       123
B   1       1           234
C   0       2       345
D   2       3       546

First it should sort based on usage count, descending order. If same usage count found then it should sort based on return code in ascending order.If same return count is found then it should sorted with number in ascending order. When i tried this below code snippet

public class SomeComparator implements Comparator<SomeVO> {
        @Override
        public int compare(SomeVO o1, SomeVO o2) {
            int value1 = o2.getUsageCount().compareTo(o1.getUsageCount());
            if (value1 == 0) {
                int value2 = o1.getNumberofReturns().compareTo(o2.getNumberofReturns());
                if (value2 == 0) {
                    return o1.getNumber().compareTo(o2.getNumber());
                } else {
                    return value2;
                }
            }
            return value1;
        }
    }

I get output D,B,C, but i am expecting it as D,B,A,C.

Upvotes: 1

Views: 91

Answers (1)

Mena
Mena

Reputation: 48404

No. You should be able to implement all sorting logic in your Comparator (or Comparable) implementation.

For instance (pseudo-code):

  • Compare by color (lexicographically apparently, i.e. your example puts "Black" before "black")
  • If equal, compare by seats

Your Collections.sort invocation will then perform the appropriate sort based on your logic within compare or compareTo.

Upvotes: 4

Related Questions