Class CollectionUtil

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 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  
13 package org.locationtech.jts.util;
14  
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Iterator;
18 import java.util.List;
19  
20 /**
21  * Utilities for processing {@link Collection}s.
22  *
23  * @version 1.7
24  */
25 public class CollectionUtil 
26 {
27  
28   public interface Function {
29     Object execute(Object obj);
30   }
31  
32   /**
33    * Executes a function on each item in a {@link Collection}
34    * and returns the results in a new {@link List}
35    *
36    * @param coll the collection to process
37    * @param func the Function to execute
38    * @return a list of the transformed objects
39    */
40   public static List transform(Collection coll, Function func)
41   {
42     List result = new ArrayList();
43     for (Iterator i = coll.iterator(); i.hasNext(); ) {
44       result.add(func.execute(i.next()));
45     }
46     return result;
47   }
48  
49   /**
50    * Executes a function on each item in a Collection but does
51    * not accumulate the result
52    *
53    * @param coll the collection to process
54    * @param func the Function to execute
55    */
56   public static void apply(Collection coll, Function func)
57   {
58     for (Iterator i = coll.iterator(); i.hasNext(); ) {
59       func.execute(i.next());
60     }
61   }
62  
63   /**
64    * Executes a {@link Function} on each item in a Collection
65    * and collects all the entries for which the result
66    * of the function is equal to {@link Boolean} <tt>true</tt>.
67    *
68    * @param collection the collection to process
69    * @param func the Function to execute
70    * @return a list of objects for which the function was true
71    */
72   public static List select(Collection collection, Function func) {
73     List result = new ArrayList();
74     for (Iterator i = collection.iterator(); i.hasNext();) {
75       Object item = i.next();
76       if (Boolean.TRUE.equals(func.execute(item))) {
77         result.add(item);
78       }
79     }
80     return result;
81   }
82 }
83