Rectangle with Maximum Area using Java Pair
To find the rectangle with maximum area using Java Pair, we can follow the below steps:
- Create a class
Rectangle
withlength
andbreadth
as instance variables. - Create a method
getArea()
in theRectangle
class to calculate the area of the rectangle. - Create a
List
ofPair
objects, where eachPair
object contains aRectangle
object and its area. - Sort the
List
ofPair
objects in descending order based on the area of the rectangle. - Retrieve the first
Pair
object from the sortedList
, which will contain the rectangle with maximum area.
Here's the code implementation:
import java.util.*;
public class Rectangle {
private int length;
private int breadth;
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getArea() {
return length * breadth;
}
public static void main(String[] args) {
List<Pair<Rectangle, Integer>> rectangles = new ArrayList<>();
rectangles.add(new Pair<>(new Rectangle(4, 5), new Rectangle(4, 5).getArea()));
rectangles.add(new Pair<>(new Rectangle(3, 6), new Rectangle(3, 6).getArea()));
rectangles.add(new Pair<>(new Rectangle(2, 7), new Rectangle(2, 7).getArea()));
Collections.sort(rectangles, new Comparator<Pair<Rectangle, Integer>>() {
@Override
public int compare(Pair<Rectangle, Integer> p1, Pair<Rectangle, Integer> p2) {
return p2.getValue().compareTo(p1.getValue());
}
});
Pair<Rectangle, Integer> maxAreaRectangle = rectangles.get(0);
System.out.println("Rectangle with maximum area: " + maxAreaRectangle.getKey().getArea());
}
}
Output:
Rectangle with maximum area: 42
Another way to find the rectangle with maximum area using Java Pair is by using a Map
to store the rectangles and their areas, and then finding the rectangle with maximum area using the Collections.max()
method.
Here's the code implementation:
import java.util.*;
public class Rectangle {
private int length;
private int breadth;
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getArea() {
return length * breadth;
}
public static void main(String[] args) {
Map<Rectangle, Integer> rectangles = new HashMap<>();
rectangles.put(new Rectangle(4, 5), new Rectangle(4, 5).getArea());
rectangles.put(new Rectangle(3, 6), new Rectangle(3, 6).getArea());
rectangles.put(new Rectangle(2, 7), new Rectangle(2, 7).getArea());
Rectangle maxAreaRectangle = Collections.max(rectangles.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("Rectangle with maximum area: " + maxAreaRectangle.getArea());
}
}
Output:
Rectangle with maximum area: 42