简体   繁体   English

如何为TreeMap和HashMap(Java)创建可迭代包装器?

[英]How to create an iterable wrapper for TreeMap and HashMap (Java)?

I have a class MyMap which wraps TreeMap. 我有一个包含TreeMap的MyMap类。 (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. 我想用for-each循环将MyMap迭代。 I know how I would've done it if my class was a LinkedList wrapper: 我知道如果我的类是LinkedList包装器我会怎么做:

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(). 但是这样的解决方案不适用于TreeMap,因为TreeMap没有迭代器()。 So how can I make MyMap iterable? 那么如何才能使MyMap可迭代?

And the same question except MyMap wraps HashMap (instead of TreeMap). 除了MyMap之外,同样的问题包含了HashMap(而不是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? 所以,我建议的是:你的Map需要有一个可迭代的吗? Not if you just want to get at the values... or the keys themselves. 如果你只是想要获得价值......或者密钥本身,那就不是了。

Also, consider using Google's forwarding collections such as ForwardingList 另外,请考虑使用Google的转发集合,例如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. map.values()是地图中包含的狗的集合视图。 The collection's iterator will return the values in the order that their corresponding keys appear in the tree. 集合的迭代器将按照其对应键出现在树中的顺序返回值。 Thanks to Jonathan Feinberg. 感谢Jonathan Feinberg。

One possibility may be to define an entrySet() method that returns a Set and then iterate over the Set. 一种可能性是定义一个entrySet()方法,该方法返回一个Set,然后迭代Set。

For-each iteration would look something like this: For-each迭代看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM