View Javadoc
1   /*
2   * Copyright (c) 2003, The JUNG Authors 
3   *
4   * All rights reserved.
5   *
6   * This software is open-source under the BSD license; see either
7   * "license.txt" or
8   * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
9   */
10  package edu.uci.ics.jung.algorithms.util;
11  
12  import java.util.Collection;
13  
14  import com.google.common.collect.BiMap;
15  import com.google.common.collect.HashBiMap;
16  
17  /**
18   * A class providing static methods useful for improving the
19   * performance of graph algorithms.
20   * 
21   * @author Tom Nelson
22   *
23   */
24  public class Indexer {
25  	
26  	/**
27  	 * Returns a <code>BiMap</code> mapping each element of the collection to its
28  	 * index as encountered while iterating over the collection. The purpose
29  	 * of the index operation is to supply an O(1) replacement operation for the
30  	 * O(n) <code>indexOf(element)</code> method of a <code>List</code>
31  	 * @param <T> the type of the collection elements
32  	 * @param collection the collection whose indices are to be generated
33  	 * @return a bidirectional map from collection elements to 0-based indices
34  	 */
35  	public static <T> BiMap<T,Integer> create(Collection<T> collection) {
36  	    return create(collection, 0);
37  	}
38  	/**
39  	 * Returns a <code>BiMap</code> mapping each element of the collection to its
40  	 * index as encountered while iterating over the collection. The purpose
41  	 * of the index operation is to supply an O(1) replacement operation for the
42  	 * O(n) <code>indexOf(element)</code> method of a <code>List</code>
43  	 * @param <T> the type of the collection elements
44  	 * @param collection the collection whose indices are to be generated
45  	 * @param start start index
46  	 * @return a bidirectional map from collection elements to start-based indices
47  	 */
48  	public static <T> BiMap<T,Integer> create(Collection<T> collection, int start) {
49  		BiMap<T,Integer> map = HashBiMap.<T,Integer>create();
50  		int i=start;
51  		for(T t : collection) {
52  			map.put(t,i++);
53  		}
54  		return map;
55  	}
56  }