How to create an iterative wrapper for TreeMap and HashMap (Java)?

I have a MyMap class that wraps TreeMap. (Say this is a collection of dogs and the keys are strings).

public class MyMap { private TreeMap<String, Dog> map; ... } 

I would like MyMap to repeat with a for-each loop. I know how I would do this 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 does not work for TreeMap, because TreeMap does not have an iterator (). So how can I make MyMap iterable?

And the same question, except for MyMap, wraps HashMap (instead of TreeMap).

Thanks.

+4
source share
4 answers
 public Iterator<Dog> iterator() { return map.values().iterator(); } 
+8
source

This is because you can only iterate over the keys or values ​​of the Map, not the map itself

You can usually do this:

 for( Object value : mymap.values() ){ System.out.println(value); } 

So what I suggest: should your card have iterability? Not if you just want to get the values ​​... or the keys themselves.

Also, consider using Google redirect collections such as ForwardingList

+6
source
 public class MyMap implements Iterable<Dog> { private TreeMap<String, Dog> map; ... @Override public Iterator<Dog> iterator() { return map.values().iterator(); } } 

map.values ​​() is a representation of the collection of dogs contained in the map. The collection iterator returns the values ​​in the order in which their corresponding keys appear in the tree. Thanks Jonathan Feinberg.

+4
source

One possibility would be to define an entrySet () method that returns Set and then iterates over Set.

For each iteration it will look something like this:

 for (Map.Entry<String,Integer> m: someMap.entrySet()){ System.out.println("Key="+m.getKey()+" value="+m.getValue()); } 
+1
source

All Articles