Class GeometryMapper

 1 /*
 2  * Copyright (c) 2016 Martin Davis.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12 package org.locationtech.jts.geom.util;
13  
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Iterator;
17 import java.util.List;
18  
19 import org.locationtech.jts.geom.Geometry;
20 import org.locationtech.jts.geom.GeometryCollection;
21  
22 /**
23  * Methods to map various collections 
24  * of {@link Geometry}s  
25  * via defined mapping functions.
26  * 
27  * @author Martin Davis
28  *
29  */
30 public class GeometryMapper 
31 {
32   /**
33    * Maps the members of a {@link Geometry}
34    * (which may be atomic or composite)
35    * into another <tt>Geometry</tt> of most specific type.
36    * <tt>null</tt> results are skipped.
37    * In the case of hierarchical {@link GeometryCollection}s,
38    * only the first level of members are mapped.
39    *  
40    * @param geom the input atomic or composite geometry
41    * @param op the mapping operation
42    * @return a result collection or geometry of most specific type
43    */
44   public static Geometry map(Geometry geom, MapOp op)
45   {
46     List mapped = new ArrayList();
47     for (int i = 0; i < geom.getNumGeometries(); i++) {
48       Geometry g = op.map(geom.getGeometryN(i));
49       if (g != null)
50         mapped.add(g);
51     }
52     return geom.getFactory().buildGeometry(mapped);
53   }
54   
55   public static Collection map(Collection geoms, MapOp op)
56   {
57     List mapped = new ArrayList();
58     for (Iterator i = geoms.iterator(); i.hasNext(); ) {
59       Geometry g = (Geometry) i.next();
60       Geometry gr = op.map(g);
61       if (gr != null)
62         mapped.add(gr);
63     }
64     return mapped;
65   }
66   
67   /**
68    * An interface for geometry functions used for mapping.
69    * 
70    * @author Martin Davis
71    *
72    */
73   public interface MapOp 
74   {
75     /**
76      * Computes a new geometry value.
77      * 
78      * @param g the input geometry
79      * @return a result geometry
80      */
81     Geometry map(Geometry g);
82   }
83 }
84