Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

public 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.

like image 423
snakile Avatar asked Dec 02 '22 06:12

snakile


1 Answers

public Iterator<Dog> iterator() {
      return map.values().iterator();
}
like image 67
Jonathan Feinberg Avatar answered Dec 05 '22 08:12

Jonathan Feinberg