Here you can find the source of mergeRects(Set
private static Set<Rectangle> mergeRects(Set<Rectangle> prev, Set<Rectangle> current)
//package com.java2s; /* Copyright (c) 2007 Olivier Chafik, All Rights Reserved * Copyright (c) 2008 Timothy Wall, All Rights Reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. *///from w w w.j a v a 2s. co m import java.awt.Rectangle; import java.util.HashSet; import java.util.Set; public class Main { private static Set<Rectangle> mergeRects(Set<Rectangle> prev, Set<Rectangle> current) { Set<Rectangle> unmerged = new HashSet<Rectangle>(prev); if (!prev.isEmpty() && !current.isEmpty()) { Rectangle[] pr = prev.toArray(new Rectangle[prev.size()]); Rectangle[] cr = current.toArray(new Rectangle[current.size()]); int ipr = 0; int icr = 0; while (ipr < pr.length && icr < cr.length) { while (cr[icr].x < pr[ipr].x) { if (++icr == cr.length) { return unmerged; } } if (cr[icr].x == pr[ipr].x && cr[icr].width == pr[ipr].width) { unmerged.remove(pr[ipr]); cr[icr].y = pr[ipr].y; cr[icr].height = pr[ipr].height + 1; ++icr; } else { ++ipr; } } } return unmerged; } }