开发者

How to iterate over the sets in a SetMultimap without a cast?

I have a SetMulti开发者_高级运维map<X> x and I need to do something with each Set<X> this map contains (I don't need the keys at this point). I can call x.asMap().values(), but unfortunately this method returns a Collection<Collection<X>>. So when iterating through this I need to cast every Collection<X> into a Set<X>:

SetMultimap<X> x;
for (Collection<X> y : x.asMap().values()) {
  foo((Set<X>)y); // foo only takes a Set<X>
}

Is there another without this cast? Of course the documentation of SetMultimap states that this cast is safe, but it would be nicer if the cast wouldn't be needed at all. The same problem occurs with a SortedSetMultimap.


a) There is no reason you should need a Set. Set has no methods beyond those specified by Collection. The collections you get are sets, but the variable types are not. Use the Collections, there is no need for casting.

b) if you do need the Set, or the SortedSet in case of a SortedSetMultimap, you have to iterate over the keys:

SetMultimap<String,Integer> mmap = Multimaps.newSetMultimap(map, supplier);
for(String key : mmap.keySet()){
    Set<Integer> set = mmap.get(key);
}

or

SortedSetMultimap<String,Integer> mmap = 
    Multimaps.newSortedSetMultimap(map, supplier);
for(String key : mmap.keySet()){
    SortedSet<Integer> sortedSet = mmap.get(key);
}


I can think of a better solution, but is not that efficient (but without cast).

for (K k : x.keySet()) {
    Set<X> a = x.get(k);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜