本文主要是【java】——遍历map的三种方法的文章,如果有什么需要改进的地方还请大佬指出⛺️
作者简介:大家好,我是听风与他
☁️博客首页:CSDN主页听风与他
每日一句:狠狠沉淀,顶峰相见
//通过Map.keySet使用iterator遍历key,然后通过key得到相应的value
Iterator<String> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
Integer value = map.get(key);
System.out.print(key+":"+value+" ");
}
//通过Map.entrySet使用iterator遍历key和value
//注意:Set entrySet():返回所有key-value对构成的Set集合
Iterator<Entry<String, Integer>> entries= map.entrySet().iterator();
while(entries.hasNext()) {
Map.Entry<String, Integer> entry = entries.next();
System.out.print(entry.getKey()+":"+entry.getValue()+" ");
}
//通过map.keySet()遍历
Set<String> set = map.keySet();
for(String key:set) {
Integer value = map.get(key);
System.out.print(key+":"+value+" ");
}
package test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Integer> map = new HashMap<>();
map.put("zhangsan", 3);
map.put("lisi", 1);
map.put("wangwu", 2);
map.put("zhaoliu", 4);
System.out.println(map);
//通过Map.keySet使用iterator遍历key,然后通过key得到相应的value
Iterator<String> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
Integer value = map.get(key);
System.out.print(key+":"+value+" ");
}
System.out.println();
//通过Map.entrySet使用iterator遍历key和value
//注意:Set entrySet():返回所有key-value对构成的Set集合
Iterator<Entry<String, Integer>> entries= map.entrySet().iterator();
while(entries.hasNext()) {
Map.Entry<String, Integer> entry = entries.next();
System.out.print(entry.getKey()+":"+entry.getValue()+" ");
}
System.out.println();
//通过map.keySet()遍历
Set<String> set = map.keySet();
for(String key:set) {
Integer value = map.get(key);
System.out.print(key+":"+value+" ");
}
}
}