遍历Map<K, Collection<V>>的正确方法

GD Star Rating
loading...

对于value为集合的map,一般直觉上我们可能会选用下面的方式遍历map中所有collection的所有对象:

for(K key:map.keySet()){
    for(V value:map.get(key)){
        // do sth.
    }
}

实际上,这种方式在第二行上会因为对哈希表的查询浪费效率,正确的做法应该这样:

  1. for(List<v> list:map.values()){
  2.     for(V o:list){
  3.         // do sth.
  4.     }
  5. }
for(List<v> list:map.values()){
    for(V o:list){
        // do sth.
    }
}

或者

  1. for(Map.Entry<k,List<v>> entry:map.entrySet()){
  2.     for(V o:entry.getValue()){
  3.         // do sth.
  4.     }
  5. }
for(Map.Entry<k,List<v>> entry:map.entrySet()){
    for(V o:entry.getValue()){
        // do sth.
    }
}

原创内容,转载请注明: 转载自拈花微笑

本文链接地址: 遍历Map<K, Collection<V>>的正确方法

685

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!:

使用新浪微博登陆

无觅相关文章插件,快速提升流量