如何迭代TreeMap?

时间:2009-08-23 16:42:26

标签: java collections treemap

  

可能重复:
  How do I iterate over each Entry in a Map?

我想迭代TreeMap,对于具有特定值的所有键,我希望将它们添加到新的TreeMap。我怎么能这样做?

4 个答案:

答案 0 :(得分:214)

假设类型为TreeMap< String,Integer> :

for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
  String key = entry.getKey();
  Integer value = entry.getValue();

  System.out.println(key + " => " + value);
}

(键和值类型当然可以是任何类)

答案 1 :(得分:25)

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");

    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

或:

   for (Map.Entry<K,V> entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

或:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

答案 2 :(得分:5)

只是指出迭代任何地图的通用方法:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
    }
    }

答案 3 :(得分:1)

使用Google Collections,假设K是您的密钥类型:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

如果您还需要值,也可以使用filterEntries