Mercer Mercer - 1 month ago 18
Java Question

Sort tables with two elements

I want to make a sort in Java. In my object I have many element so I want to make this sort with power and model:

public class Product implements Comparable<Product>,Serializable
{
private int idProduct ;
private int power;
private String model;
private String color;
[...]
@Override
public int compareTo(Product o) {
return String.valueOf(this.power).compareTo(String.valueOf(o.power));

}


So how to make sort with power and model?

Answer

The following will first sort on power and in case of a tie, will sort on model:

public int compareTo(Product that) {
  if(this.power != that.power) {
    return this.power < that.power ? -1 : 1;
  } 
  else {
    return this.model.compareTo(that.model);
  }
}

Or if you need to compare power lexicographically, do:

public int compareTo(Product that) {
  if(this.power != that.power) {
    return String.valueOf(this.power).compareTo(String.valueOf(that.power));
  } 
  else {
    return this.model.compareTo(that.model);
  }
}