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:
I frequently see people do this without entrySet(), and it usually looks something like this:
- for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
- Foo key = (Foo) it.next();
- Bar value = (Bar) map.get(key);
- // now do something with key and value
- }
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.
- for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
- Map.Entry e = (Map.Entry) it.next();
- Foo key = (Foo) e.getKey();
- Bar value = (Bar) e.getValue();
- // now do something with key and value
- }
Under JDK 5 and later it's a little nicer:
- for (Map.Entry<Foo,Bar> e : map.entrySet()) {
- Foo key = e.getKey();
- Bar value = e.getValue();
- // now do something with key and value
- }
本文介绍了在Java中高效遍历Map的方法。如果只需要键或值,推荐使用keySet()或values();若同时需要键和值,则应选择entrySet()以避免重复查找,提高效率。在JDK 5及更高版本中,利用增强型for循环可以更简洁地实现这一目标。
3041

被折叠的 条评论
为什么被折叠?



