如何迭代一个TreeMap?

可能重复:
如何迭代Map中的每个条目?

我想遍历一个TreeMap ,并为所有具有特定值的键,我想他们被添加到一个新的TreeMap 。 我怎样才能做到这一点?

假设types为TreeMap <String,Integer>:

 for(Map.Entry<String,Integer> entry : treeMap.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + " => " + value); } 

(键和值types可以是任何课程)

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

只是指出遍历任何映射的通用方法:

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

使用Google Collections ,假设K是您的关键types:

 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