Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...