Java中的Map遍歷

2021-08-03 09:22:55 字數 2079 閱讀 3437

在map集合中

values():獲取集合中的所有的值,沒有鍵,沒有對應關係;

keyset():

將map中所有的鍵存入到set集合中。因為set具備迭代器,所以可以用迭代方式取出所有的鍵,再根據get方法,獲取每乙個鍵對應的值。

entryset():set> entryset()返回此對映中包含的對映關係的set檢視。map.entry表示對映關係。entryset():迭代後可以用e.getkey(),e.getvalue()取key和value。

例子:values():

mapmap = new hashmap();

map.put("01", "zhangsan");

map.put("02", "lisi");

map.put("03", "wangwu");

collectioncollection = map.values();//返回值是個值的collection集合

system.out.println(collection);

列印結果:

[zhangsan, lisi, wangwu]

keyset():

mapmap = new hashmap();

map.put("01", "zhangsan");

map.put("02", "lisi");

map.put("03", "wangwu");

setkeyset = map.keyset();//先獲取map集合的所有鍵的set集合

iteratorit = keyset.iterator();//有了set集合,就可以獲取其迭代器。

while(it.hasnext())

entryset():

mapmap = new hashmap();

map.put("01", "zhangsan");

map.put("02", "lisi");

map.put("03", "wangwu");

//通過entryset()方法將map集合中的對映關係取出(這個關係就是map.entry型別)

set> entryset = map.entryset();

//將關係集合entryset進行迭代,存放到迭代器中

iterator> it2 = entryset.iterator();

while(it2.hasnext())

雖然使用keyset及entryset來進行遍歷能取得相同的結果

,但兩者的遍歷速度是有差別的

keyset():迭代後只能通過get()取value

entryset():迭代後可以通過e.getkey(),e.getvalue()取key和value,返回的是entry介面 

說明:keyset()的速度比entryset()慢了很多,也就是keyset方式遍歷map的效能不如entryset效能好,

為了提高效能,以後多考慮用entryset()方式來進行遍歷。

另乙個例子:

public static void main(string args) 

//第二種

system.out.println("通過map.entryset使用iterator遍歷key和value:");

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

while (it.hasnext())

//第三種:推薦,尤其是容量大時

system.out.println("通過map.entryset遍歷key和value");

for (map.entryentry : map.entryset())

//第四種

system.out.println("通過map.values()遍歷所有的value,但不能遍歷key");

for (string v : map.values())

}

java中Map的遍歷

map遍歷的常用方法 mapmap new hashmap map.put 0,zero map.put 1,one map.put 2,two 方法一 最常用的 獲取key值 collectionk map.keyset iteratoritk k.iterator system.out.prin...

Java 中 Map 的遍歷

jdk1.4中 map map new hashmap iterator it map.entryset iterator while it.hasnext jdk1.5中,應用新特性for each迴圈 map m new hashmap for object o map.keyset 返回的 s...

關於JAVA中Map集合的遍歷

每次用到map集合的時候都要去查一下怎麼遍歷,最近一次查的,感覺還不錯,收藏吧!第一種 map string,string map new hashmap string,string for entry string,string entry map entryset 第二種 iterator.en...