Java 如何遍历 TreeMap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1318980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:11:25  来源:igfitidea点击:

How to iterate over a TreeMap?

javacollectionstreemap

提问by Click Upvote

Possible Duplicate:
How do I iterate over each Entry in a Map?

可能的重复:
如何遍历地图中的每个条目?

I want to iterate over a TreeMap, and for all keys which have a particular value, I want them to be added to a new TreeMap. How can I do this?

我想迭代 a TreeMap,并且对于具有特定值的所有键,我希望将它们添加到新的TreeMap. 我怎样才能做到这一点?

采纳答案by Zed

Assuming type TreeMap<String,Integer> :

假设类型 TreeMap<String,Integer> :

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

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

(key and Value types can be any class of course)

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

回答by karim79

    //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());

or:

或者:

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

or:

或者:

   // 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);
   }

回答by Jorn

Using Google Collections, assuming K is your key type:

使用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
  }});

You can use filterEntriesinstead if you need the value as well.

filterEntries如果您也需要该值,则可以改用它。

回答by Priyank Doshi

Just to point out the generic way to iterate over any map:

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

 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());
    }
    }