遍历HashMap

本文介绍如何使用迭代器遍历HashMap,包括创建Set实例并获取迭代器的过程,以及如何通过Map.Entry接口获取键值对。

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

在应用中碰到了要遍历HashMap的情况。总结一下。

先上图。

用cycle创建了一个Set的实例enn。

用enn的iterator()返回一个迭代器Iterator。此时的迭代器是一个Key—Value对。

所以需要Map.Entry entry = itt.next()。


一下摘自JDK1.7


public static interface Map.Entry<K,V>
A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.

可到Map.entry的实例时候,就可以用他的getKey和getValue方法分别获取一个键值对里的Key和Value了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值