View Javadoc

1   /* Taken 2008 from Limewire -project under the following terms: 
2    *
3    * This program is free software: you can redistribute it and/or modify
4    * it under the terms of the GNU General Public License as published by
5    * the Free Software Foundation, either version 3 of the License, or
6    * (at your option) any later version.
7    *
8    * This program is distributed in the hope that it will be useful,
9    * but WITHOUT ANY WARRANTY; without even the implied warranty of
10   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11   * GNU General Public License for more details.
12   *
13   * You should have received a copy of the GNU General Public License
14   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15   */
16  package net.sf.eos.trie;
17  
18  import java.util.ArrayList;
19  import java.util.List;
20  import java.util.Map.Entry;
21  
22  import net.sf.eos.trie.Trie.Cursor;
23  
24  
25  
26  /**
27   * Miscellaneous utilities for Tries. See <a 
28   * href="http://en.wikipedia.org/wiki/Trie">Trie</a> for more information.
29   * <p><strong>Note:</strong> Taken from 
30   * <a href='http://www.limewire.org/'>Limewire</a> sourcecode and repackaged by
31   * Sascha Kohlmann.</p>
32   */
33  public final class TrieUtils {
34      
35      private TrieUtils() {}
36      
37      public static <K,V> List<V> select(Trie<K,V> trie, K key, int count) {
38          return select(trie, key, count, null);
39      }
40      
41      public static <K,V> List<V> select(Trie<K,V> trie, K key, 
42                  int count, final Cursor<K,V> cursor) {
43          
44          final int size = Math.min(trie.size(), count);
45          final List<V> values = new ArrayList<V>(size);
46          
47          trie.select(key, new Cursor<K,V>() {
48              public Cursor.SelectStatus select(Entry<? extends K, ? extends V> entry) {
49                  if (cursor == null || cursor.select(entry) == Cursor.SelectStatus.EXIT) {
50                      values.add(entry.getValue());
51                  }
52                  
53                  return values.size() >= size ? Cursor.SelectStatus.EXIT : Cursor.SelectStatus.CONTINUE;
54              }
55          });
56          
57          return values;
58      }
59  }