View Javadoc
1   /*
2    * Created on May 19, 2008
3    *
4    * Copyright (c) 2008, The JUNG Authors 
5    *
6    * All rights reserved.
7    *
8    * This software is open-source under the BSD license; see either
9    * "license.txt" or
10   * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
11   */
12  package edu.uci.ics.jung.algorithms.filters;
13  
14  import com.google.common.base.Predicate;
15  
16  import edu.uci.ics.jung.graph.Graph;
17  
18  /**
19   * Transforms the input graph into one which contains only those edges 
20   * that pass the specified <code>Predicate</code>.  The filtered graph
21   * is a copy of the original graph (same type, uses the same vertex and
22   * edge objects).  All vertices from the original graph
23   * are copied into the new graph (even if they are not incident to any
24   * edges in the new graph).
25   * 
26   * @author Joshua O'Madadhain
27   */
28  public class EdgePredicateFilter<V, E> implements Filter<V, E>
29  {
30      protected Predicate<E> edge_pred;
31  
32      /**
33       * Creates an instance based on the specified edge <code>Predicate</code>.
34       * @param edge_pred   the predicate that specifies which edges to add to the filtered graph
35       */
36      public EdgePredicateFilter(Predicate<E> edge_pred)
37      {
38          this.edge_pred = edge_pred;
39      }
40      
41      @SuppressWarnings("unchecked")
42      public Graph<V,E> apply(Graph<V,E> g)
43      {
44          Graph<V, E> filtered;
45          try
46          {
47              filtered = g.getClass().newInstance();
48          }
49          catch (InstantiationException e)
50          {
51              throw new RuntimeException("Unable to create copy of existing graph: ", e);
52          }
53          catch (IllegalAccessException e)
54          {
55              throw new RuntimeException("Unable to create copy of existing graph: ", e);
56          }
57  
58          for (V v : g.getVertices())
59              filtered.addVertex(v);
60          
61          for (E e : g.getEdges())
62          {
63              if (edge_pred.apply(e))
64                  filtered.addEdge(e, g.getIncidentVertices(e));
65          }
66          
67          return filtered;
68      }
69  
70  }