I have a list of AWT rectangles. I want to compute the union of the rectangles in an elegant way. Here is my code which works but does not look very elegant.
Rectangle union(List<Rectangle> rects) {
if (rects.isEmpty()) {
return new Rectangle();
}
assert !rects.isEmpty();
final Iterator<Rectangle> iterator = rects.iterator();
Rectangle rect = iterator.next();
while (iterator.hasNext()) {
rect = rect.union( iterator.next() );
}
return rect;
}
I also tried the following which does not work:
Rectangle union(List<Rectangle> rects) {
Rectangle result = new Rectangle();
for (Rectangle rect : rects) {
result.add( rect );
}
return result;
}
The rectangle result is initialized to (0,0,0,0) so the union will allways contain the origin.
Is there a more elegant way to do this in Java?