How to create an iterable wrapper for TreeMap and HashMap (Java)?
I have a class MyMap which wraps TreeMap. (Say it's a collection of dogs and that the keys are strings).
publ开发者_开发技巧ic class MyMap {
private TreeMap<String, Dog> map;
...
}
I would like to turn MyMap iterable with the for-each loop. I know how I would've done it if my class was a LinkedList wrapper:
public class MyList implements Iterable<Dog> {
private LinkedList<Dog> list;
...
public Iterator<Dog> iterator() {
return list.iterator();
}
}
But such a solution doesn't work for TreeMap because TreeMap doesn't have an iterator(). So how can I make MyMap iterable?
And the same question except MyMap wraps HashMap (instead of TreeMap).
Thanks.
public Iterator<Dog> iterator() {
return map.values().iterator();
}
It's because you can only iterate the keys or the values of a Map, not the map itself
Typically you can do this:
for( Object value : mymap.values() ){
System.out.println(value);
}
So, what I'm suggesting is: does your Map need to have an iterable? Not if you just want to get at the values... or the keys themselves.
Also, consider using Google's forwarding collections such as ForwardingList
public class MyMap implements Iterable<Dog> {
private TreeMap<String, Dog> map;
...
@Override
public Iterator<Dog> iterator() {
return map.values().iterator();
}
}
map.values() is a collection view of the dogs contained in map. The collection's iterator will return the values in the order that their corresponding keys appear in the tree. Thanks to Jonathan Feinberg.
One possibility may be to define an entrySet() method that returns a Set and then iterate over the Set.
For-each iteration would look something like this:
for (Map.Entry<String,Integer> m: someMap.entrySet()){
System.out.println("Key="+m.getKey()+" value="+m.getValue());
}
精彩评论