Remove/Fill holes in Polygons from a MultiPolygon using JTS Topology Suite programmatically

OpenJUMP has a "remove holes" tool (and an advanced "remove small holes" tool as well). OpenJUMP often uses JTS rather directly but I am not sure about this case. The source code of the function is at https://sourceforge.net/p/jump-pilot/code/HEAD/tree/core/trunk/src/com/vividsolutions/jump/workbench/ui/plugin/analysis/GeometryFunction.java

The idea seems to be simple: Get the list of polygons, get the exterior rings and create new polygons from those. Inner rings disappear and job is done.

  // added on 2016-11-11 by mmichaud
  private static class RemoveHolesFunction extends GeometryFunction {
    public RemoveHolesFunction() {
      super(I18N.get("ui.plugin.analysis.GeometryFunction.Remove-Holes"), 1, 0);
    }

    public Geometry execute(Geometry[] geom, double[] param)
    {
      AbstractGeometryProcessor removeHoleProcessor = new AbstractGeometryProcessor() {
        public void process(Polygon polygon, List<Geometry> list) {
          list.add(polygon.getFactory().createPolygon((LinearRing)polygon.getExteriorRing()));
        }
      };
      return removeHoleProcessor.process(geom[0]);
    }
  }

Basically, you need to create a new Polygon from the ExteriorRing of the input Polygon.

gf.createPolygon(p.getExteriorRing().getCoordinateSequence());

There is a little more work with MultiPolygons as you have to handle each subpolygon in turn. The whole method becomes something like:

  static GeometryFactory gf = new GeometryFactory();
  static public Geometry removeHoles(Geometry g) {

    if (g.getGeometryType().equalsIgnoreCase("Polygon")) {
      Polygon p = (Polygon) g;
      return gf.createPolygon(p.getExteriorRing().getCoordinateSequence());
    } else if (g.getGeometryType().equalsIgnoreCase("MultiPolygon")) {

      MultiPolygon mp = (MultiPolygon) g;
      List<Polygon> polys = new ArrayList<>();
      for (int i = 0; i < mp.getNumGeometries(); i++) {
        Polygon poly = gf.createPolygon(((Polygon) mp.getGeometryN(i)).getExteriorRing().getCoordinateSequence());
        polys.add(poly);
      }
      return gf.createMultiPolygon(polys.toArray(new Polygon[] {}));

    }

    return g;
  }