0

I need to sort Rectangle objects in my ArrayList list1 by their corresponding properties: height,width, and topCorner(Point). I am able to sort the list when evaluating one property.

How can I set up my compareTo method so that it first attempts to sort the objects in the list by height, then by width(if all object heights are equal), and finally bytopCorner(if all object heights and widths are equal)?

public class Point implements Comparable<Point> {

private int x;
private int y;

public Point(){
    this(0,0);
}
public Point(int x,int y){
    this.x=x;
    this.y=y;
}
public int getX(){
    return x;
}
public int getY(){
    return y;
}
public int compareTo(Point pt){
    if(x==pt.x){
        return y-pt.y;
    }
    else{
        return x-pt.x;
    }
}
public String toString(){
    return "("+x+", "+y+")";
}
}
class Rectangle implements Comparable<Rectangle> {

private int height;
private int width;
private Point topCorner;

public Rectangle(int x,int y,int height,int width){
    this.height=height;
    this.width=width;
    this.topCorner=new Point(x,y);
}
public int getHeight(){
    return height;
}
public int getWidth(){
    return width;
}
public Point getPoint(){
    return topCorner;
}
public int compareTo(Rectangle rect){
    if(height!=rect.height){
        int compareHeight=((Rectangle)rect).getHeight();
        return this.height-compareHeight;
    }
    else if(width!=rect.width){
        int compareWidth=((Rectangle)rect).getWidth();
        return this.width-compareWidth;
    }
    else if(topCorner!=rect.topCorner){
        Point comparePoint=((Rectangle)rect).getPoint();
        return this.topCorner-topCorner;
    }
    else{
        System.out.println("// ERROR BRO // ERROR BRO //");
    }
    return 0;
}
public String toString(){
    return "(H:"+height+", W:"+width+", P:"+topCorner+")";
}
}

===========================================================================

public class RectangleComparable {
public static void main(String[]args){
    Random rn=new Random(21);
    ArrayList<Rectangle> list1=new ArrayList<>();
    for(int index=0;index<10;index++){
        int ran1=rn.nextInt(21), ran2=rn.nextInt(21),
                ran3=rn.nextInt(21), ran4=rn.nextInt(21);
        list1.add((new Rectangle(5,ran2,ran3,ran4)));
    }
    System.out.println("KEY : H=height, W=width, P=point\n");
    System.out.println("Unsorted List : \n"+list1+"\n");
    Collections.sort(list1);
    System.out.println("Sorted List : \n"+list1);
}
}

I'll go ahead and apologize if this is somehow a duplicate question. I looked around, but I didn't find anything that gave me a really direct answer (because I'm still a programming noob).

1 Answers1

1

You can write your own Comparator or build one as follows:

Comparator
    .comparingInt(Rectangle::getHeight)
    .thenComparingInt(Rectangle::getWidth)
    .thenComparing(Rectangle::getTopCorner);
lexicore
  • 42,748
  • 17
  • 132
  • 221