I have a problem in my code. I Have abstract class Shape implements Comparable, and Classes like Rectangle etc. I want to sort my List of Shapes. One by Area and if I call method it will be by Name for example.. How to do this?
public int compareTo(Shape shape) {
return Integer.compare(shape.area(), area());
}
and It is good. Everything is working but how to do call in Main something like this: Shape.SortBy(Shape.NAME) and its method should sort now by Name not by Area..
CodePudding user response:
Similar as you want to sort by different criteria you may want to compare according to different criteria. In this case make use of the Comparator pattern which allows stuff like this:
Arrays.sort(shapes, myComparator);
CodePudding user response:
I am unsure about the class, but you can use Comparator. It has several useful forms.
List<Shape> shapes = ...;
shapes.sort(Comparator.comparingInt(Shape::getArea));
shapes.sort(Comparator.comparingInt(sh -> sh.getWidth() * sh.getHeight()));
shapes.sort(Comparator.comparingInt(Shape::getWidth)
.thenComparingInt(Shape::getHeight));
shapes.sort(Comparator.comparing(Shape::getName).reversed());
shapes.sort(Comparator.comparing(sh -> sh.name));
Above the usage of Comparator with a function delivering the key value to compare, for both left hand side and right hand side. Either with method reference or lambda.