Why use Map.entrySet() instead of Map.keySet()?

本文介绍了在Java中高效遍历Map的方法。如果只需要键或值,推荐使用keySet()或values();若同时需要键和值,则应选择entrySet()以避免重复查找,提高效率。在JDK 5及更高版本中,利用增强型for循环可以更简洁地实现这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
If you just need keys, use keySet(). If you just need values, use values(). If you're going to use keys and values in your subsequent code, then you're best off using entrySet().

I frequently see people do this without entrySet(), and it usually looks something like this:
  1. for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {  
  2.     Foo key = (Foo) it.next();  
  3.     Bar value = (Bar) map.get(key);  
  4.     // now do something with key and value  
  5. }  

This works, but it's making the JVM do extra work for no good reason. Every time you call get() you're making the JVM spend time doing a hashcode lookup, or navigating a tree and evaluating a comparator. These operations may be fast, or not, but why do them if you don't have to? A Map.Entry gives you both key and value,   together, in the most efficient manner possible.
  1. for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {  
  2.     Map.Entry e = (Map.Entry) it.next();  
  3.     Foo key = (Foo) e.getKey();  
  4.     Bar value = (Bar) e.getValue();  
  5.     // now do something with key and value  

Under JDK 5 and later it's a little nicer:
  1. for (Map.Entry<Foo,Bar> e : map.entrySet()) {  
  2.     Foo key = e.getKey();  
  3.     Bar value = e.getValue();  
  4.     // now do something with key and value  
  5. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值