像Python字典一样循环Java HashMap?
在 Python 中,您可以在字典中包含键、值对,您可以在其中循环遍历它们,如下所示:
for k,v in d.iteritems():
print k,v
有没有办法使用 Java HashMap 来做到这一点?
In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的 - 例如:
Yes - for example:
HashMap.entrySet () 将返回类似于字典的键值对 bean。 iteritems()。然后您可以循环遍历它们。
我认为是最接近Python版本的。
The HashMap.entrySet() will return beans of key value pairs similar to the dictionary.iteritems(). You can then loop through them.
I think is the closest thing to the Python version.
如答案所示,基本上有两种方法来迭代
Map
(在这些示例中假设为Map
)。迭代
Map#entrySet()
:迭代
Map#keySet()
,然后使用Map#get()
获取每个键的值:第二个可能更具可读性,但它会在每次迭代时不必要地调用
get()
,从而带来性能成本。有人可能会认为创建键集迭代器的成本较低,因为它不需要考虑值。但无论您相信与否,keySet().iterator()
创建并使用与entrySet().iterator()
相同迭代器。唯一的区别是,对于keySet()
,迭代器的next()
调用返回it.next().getKey()
> 而不是it.next()
。AbstractMap#keySet ()
的 javadoc 证明了这一点:AbstractMap
源代码也证明了这一点。下面是keySet()
方法的摘录(Java 1.6 中第 300 行左右):请注意,可读性应该优先于过早优化,但记住这一点很重要。
As shown in the answers, there are basically two ways to iterate over a
Map
(let's assumeMap<String, String>
in those examples).Iterate over
Map#entrySet()
:Iterate over
Map#keySet()
and then useMap#get()
to get the value for every key:The second one is maybe more readable, but it has a performance cost of unnecessarily calling
get()
on every iteration. One may argument that creating the keyset iterator is less expensive because it doesn't need to take values into account. But believe it or not, thekeySet().iterator()
creates and uses the same iterator asentrySet().iterator()
. The only difference is that in case of thekeySet()
thenext()
call of the iterator returnsit.next().getKey()
instead ofit.next()
.The
AbstractMap#keySet()
's javadoc proves this:The
AbstractMap
source code also proves this. Here's an extract ofkeySet()
method (somewhere around line 300 in Java 1.6):Note that readability should be preferred over premature optimization, but it's important to have this in mind.
类似的事情...
Something like that...
在 Java 中,您可以执行以下相同操作。
In Java, you can do the same like the following.