Java: Implement Compararable but too many conditional ifs. How can I avoid them?

I have a list of objects which implement Comparable.

I want to sort this list and that is why I used the Comparable.

Each object has a field, weight that is composed of 3 other member int variables.

The compareTo returns 1 for the object with the most weight.
The most weight is not only if the

weightObj1.member1 > weightObj2.member1 weightObj1.member2 > weightObj2.member2 weightObj1.member3 > weightObj2.member3

but actually is a little more complicated and I end up with code with too many conditional ifs.

If the weightObj1.member1 > weightObj2.member1 holds then I care if weightObj1.member2 > weightObj2.member2.

and vice versa.

else if weightObj1.member2 > weightObj2.member2 holds then I care if weightObj1.member3 > weightObj2.member3 and vice versa.

Finally if weightObj1.member3 > weightObj2.member3 holds AND if a specific condition is met then this weightObj1 wins and vice versa

I was wondering is there a design approach for something like this?

-------------Problems Reply------------

The API for Comparable states:

It is strongly recommended (though not required) that natural orderings be consistent with equals.

Since the values of interest are int values you should be able to come up with a single value that captures all comparisons and other transformations you need to compare two of your objects. Just update the single value when any of the member values change.

You can try with CompareToBuilder from Apache commons-lang:

public int compareTo(Object o) {
MyClass myClass = (MyClass) o;
return new CompareToBuilder()
.append(this.field1, myClass.field1)
.append(this.field2, myClass.field2)
.append(this.field3, myClass.field3)

See also

  • How write universal comparator which can make sorting through all necessary fields?
  • Group Comparator, Bean Comparator and Column Comparator

Similar to the above-mentioned Apache CompareToBuilder, but including generics support, Guava provides ComparisonChain:

public int compareTo(Foo that) {
return ComparisonChain.start()
.compare(this.aString, that.aString)
.compare(this.anInt, that.anInt)
.compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
// you can specify comparators

You can try using reflection, iterate over properties and compare them.

You can try something like this:

int c1 = o1.m1 - o2.m1;
if (c1 != 0) {
return c1;

int c2 = o1.m2 - o2.m2;
if (c2 != 0) {
return c2;

return o1.m3 - o2.m3;

because comparable shall not just return -1, 0 or 1. It can return any integer value and only the sign is considered.

Category:java Views:1 Time:2012-01-21

Related post

  • Is there a type-safe Java implementation of 'reduce'? 2008-10-21

    I often need to run reduce (also called foldl / foldr, depending on your contexts) in java to aggregate elements of an Itterable. Reduce takes a collection/iterable/etc, a function of two parameters, and an optional start value (depending on the impl

  • Free C/C++ and Java implementations of PPP? 2009-04-26

    Are there free C/C++ and Java implementations of the point-to-point protocol (PPP) for use over a serial line? The C/C++ implementation will go into embedded hardware so portability is a concern. I'm not looking for a full TCP/IP stack, just somethin

  • Java implementation for Min-Max Heap? 2009-07-08

    Do you know of a popular library (apache collections, google collections, etc...) which has a reliable Java implementation for a Min-Max heap? I.e. a heap which allows to peek at its minimum and maximum value in O(1) and to remove at O(logn). I did a

  • java: implementation of topological sort, from a reputable source 2009-09-28

    I'm looking for a reputable Java implementation of a topological sort, given a directed graph of dependencies (node #7 depends on node #2, node #2 depends on note #4, etc.), that will detect the presence of a cycle so I can report an error if a cycle

  • ebXml OpenSource java implementation 2009-10-29

    In our project we are looking for an OpenSource java implementation of the OASIS ebXml Registry 3.0 Specification (spec). It seems there is not a lot of OpenSource initiative for this standard, actually we only found freebXml Registry which is self-n

  • How does Java implement hash tables? 2009-10-29

    Does anyone know how Java implements its hash tables (HashSet or HashMap)? Given the various types of objects that one may want to put in a hash table, it seems very difficult to come up with a hash function that would work well for all cases. ------

  • Java implementation of time to words conversion (RoR's distance_of_time_in_words and time_ago_in_words) 2010-02-25

    Do you know if it exists a java implementation of distance_of_time_in_words and time_ago_in_words? For those who don't know, these methods return a human readable description of the time interval between two dates or between a date and now. By exampl

  • OLEDate java implementation 2010-04-08

    I need a good OLEDate java implementation, and this one does not seem to be working. Is there any known good opensource implementations (like in apache commons)? If not, where do I read about it, so that I write my own implementation? --------------S

  • Is there any open source ISO 11703 java implementation? 2010-07-12

    Hey, I'm looking for an java implementation of the ISO 11073 standard (Health informatics - Point of care medical device communication), especially the Medical package of it. --------------Solutions------------- My intuition and google tell me, there

  • Is there a java implementation of Porter2 stemmer 2010-12-09

    Do you know any java implementation of the Porter2 stemmer(or any better stemmer written in java)? I know that there is a java version of Porter(not Porter2) here : but on

  • java implementation for LDPC codes 2011-03-17

    Is there any open source java implementation for LDPC(Low Density Parity Check)codes,i found only MAT lab codes. My scenario is i will take text file and divide into block and i will delete some data in text file, and by using LDPC codes i need to re

  • JSONRPC Java implementation 2011-04-05

    I've found tons of JSONRPC Java implementations out there, most of them quite old. Hence my question: which library is up to date and futureproof? --------------Solutions------------- JPoxy (at seems to be up-to-date

  • How to express 2n as sum of n variables (Java implementation?) 2011-04-14

    I wonder if there is an elegant way to derive all compositions of 2n as the sum of n non-negative integer variables. For example, for n = 2 variables x and y, there are 5 compositions with two parts : x = 0 y = 4; x = 1 y = 3; x = 2 y = 2; x = 3 y =

  • Is there a standard Java implementation of a Fibonacci heap? 2011-06-08

    I was looking at the different kind of heap data structures. The Fibonacci heap seems to have the better worst case complexity for (1) insertion, (2) deletion and (2) finding the minimum element. I have found that in Java there is a class PriorityQue

  • Webservice Notification - what java implementation would you recommend? 2011-06-25

    I'm looking to listen to WSN produced by a .net webservice using java. What java implementation for WSN would you recommend in this case? --------------Solutions------------- Notification (or even Solicit response message exchange patterns) are not s

  • Java implementation of Long.numberOfTrailingZeros() 2011-06-28

    Link to documentation: Here is the Java implementation source code: /** * Returns the number of zero bits following the lowest-order ("rightmost") * one-

  • Bidirectional JSON-RPC over TCP socket Java implementation 2011-06-29

    Does anyone know if some Java implementation of the JSON-RPC protocol exists with bidirectional support (there is no Client/Server, both entities can send and receive the same messages). I know it exists in Python: bjsonrpc Thanks! --------------Solu

  • Java implementation of singular value decomposition for large sparse matrices 2011-07-25

    I'm just wondering if anyone out there knows of a java implementation of singular value decomposition (SVD) for large sparse matrices? I need this implementation for latent semantic analysis (LSA). I tried the packages from UJMP and JAMA but they cho

  • Where can i get a Java implementation of Dijkstra's algorithm? 2011-08-25

    I am looking for a generic Java implementation of Dijkstra's algorithm. I've tried coding this up on my own, but I keep running into problems. If it helps, I know for a fact that the graph is always connected. Does anyone know of such an implementati

Copyright (C), All Rights Reserved.

processed in 0.078 (s). 11 q(s)