Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

java - 遍历HashMap [重复](Iterate through a HashMap [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

What's the best way to iterate over the items in a HashMap ?

(迭代HashMap的项目的最佳方法是什么?)

  ask by burntsugar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're only interested in the keys, you can iterate through the keySet() of the map:

(如果您仅对键感兴趣,则可以遍历地图的keySet() :)

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values() :

(如果只需要这些值,请使用values() :)

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet() :

(最后,如果您想要键和值,请使用entrySet() :)

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer ).

(一个警告:如果要在迭代中删除项目,则需要通过Iterator进行删除(请参阅karim79的答案 )。)

However, changing item values is OK (see Map.Entry ).

(但是,更改项目值是可以的(请参见Map.Entry )。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...