2

Say I have a array which holds 10 objects each with 3 values supposed to represent a league table

Team1 20 5
Team2 21 6
Team3 21 8
Team4 23 8

I want to sort by the first value (points) and then by the 2nd value (goal difference).

Arrays.sort() would work if I override the compareto() and write a piece of custom code.

Is there a easier way? By converting to a list etc.?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
David Adlington
  • 666
  • 4
  • 15
  • 27

3 Answers3

9

Creating a Comparator is the correct way to solve this. Whether you then use Arrays.sort() or Collections.sort() is up to you.

I would suggest the former avoids a conversion to a list and is thus preferable.

I recommend you don't solve this by implementing Comparable in your object, as this sounds like a display issue and embedding a sort order in the object itself is probably not wise.


An example (untested) implementation might be:

public class ExampleComparator implements Comparator<YourObject> {

  public int compare(YourObject o1, YourObject o2) {
    if (o1 == null || o2 == null) {
      throw new NullPointerException();
    }

    if (o1.getValue1() != o2.getValue1()) {
      return Integer.compare(o1.getValue1(), o2.getValue1());
    }

    return Integer.compare(o1.getValue2(), o2.getValue2());
  }
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
0

There is not any generic in java, that would allow you to perform sort with multiple parameters. You have to implement your own sorting alogrithm or create your own Comparator. For more details, you should have a look at this post.

Community
  • 1
  • 1
Martin Dvoracek
  • 1,714
  • 6
  • 27
  • 55
0

There is no shortcut to this; convert your data to a class and override compareTo method.

Class Bean implements Comparable<Bean>{
  //attributes
  @Override
  public int compareTo(Object o) {
    // TODO Auto-generated method stub
    return 0;
 }
} 

Then you can put you bean object in the list and do sorting..

List<Bean> list = new ArrayList<Bean>();
rai.skumar
  • 10,309
  • 6
  • 39
  • 55