關於JAVA中Map集合的遍歷

2021-07-09 12:32:30 字數 1209 閱讀 4915

每次用到map集合的時候都要去查一下怎麼遍歷,最近一次查的,感覺還不錯,收藏吧!

第一種:

map

<

string, string

>

map=

new hashmap<

string, string

>();

for (entry<

string, string

> entry : map

.entryset())

第二種:

iterator.entry

> iterator = map.entryset().iterator();

while (iterator.hasnext())

第三種:

map

<

string, string

>

map=

new hashmap<

string, string

>();

for (string key : map

.keyset())

第四種:

set

string, string>> entryset = map.entryset();

for (entry entry : entryset)

關鍵的來啦:

a. hashmap的迴圈,如果既需要key也需要value,直接用

map<

string, string

>

map=

new hashmap<

string, string

>();

for (entry<

string, string

> entry : map

.entryset())

b. 如果只是遍歷key而無需value的話,可以直接用

map<

string, string

>

map=

new hashmap<

string, string

>();

for (string key : map

.keyset())

原文請看這裡:

java 遍歷map集合

map遍歷 jdk api對map遍歷的支援 set entryset 返回此對映所包含的對映關係的 set 檢視。setkeyset 返回此對映中所包含的鍵的 set 檢視。都是返回set檢視,但乙個是對映關係的,乙個是對映所包含鍵的set檢視。注意返回的是無序。對於這兩個方法理解可以看看demo...

Java的Map集合遍歷

方法1 通過鍵獲取值,進行鍵和值的遍歷 mapmap new hashmap for string key map.keyset 方法2 利用map集合的entryset 方法進行遍歷 mapmap new hashmap for entryentry map.entryset 方法3 利用迭代器i...

Java 遍歷Map集合的各種姿勢

最常用,在鍵值都需要時使用。mapmap new hashmap for map.entryentry map.entryset 複製 在for each迴圈中遍歷keys或values。mapmap new hashmap 遍歷map中的鍵 for integer key map.keyset 遍...