I want to iterate over a treeMap, and for all 'key's which have a particular value, I want them to be added to a new TreeMap. How can i do this? Code samples would be prefered.
+2
A:
//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);
}
karim79
2009-08-23 16:47:51
+4
A:
Assuming type 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)
Zed
2009-08-23 16:50:06
FYI, EntrySet is the preferred way to iterate through any Map since EntrySets are by specification reflective and always represent the state of data in the Map even if the Map underneath would change.
Esko
2009-08-23 16:58:57
Preferred by who?
Zed
2009-08-23 17:21:31
A:
Using Google Collections, assuming K is your key type:
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 filterEntries
instead if you need the value as well.
Jorn
2009-08-23 17:03:07