Map集合的两种遍历方式(java)
Map集合基本方法
map.put():放入元素
map.get():通过填入key值获取value
map.remove():通过填入key值移除对应键值对<K,V>
map.containsKey():判断map是否包含某一Key值
map.containsValue():判断map是否包含某一Value值
//获取所有的values
Collection<String> values=map.values();
for (String s:values){
System.out.println(s);
}
示例如下:
public class MapTest01 {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<>();
map.put(1,"zs");
map.put(2,"ls");
map.put(3,"zl");
String value=map.get(2);
System.out.println(value);
System.out.println("数量"+map.size());
map.remove(2);
System.out.println("数量"+map.size());
System.out.println(map.containsKey(3));
System.out.println(map.containsValue("ls"));
//获取所有的values
Collection<String> values=map.values();
for (String s:values){
System.out.println(s);
}
}
}
遍历方式1
构造Map集合并加入元素
Map<Integer,String> map=new HashMap<>();
map.put(1,"zs");
map.put(2,"ls");
map.put(3,"zl");
①迭代器
1.调用map.keyset(),获取返回值为Set类型的集合
Set<Integer> keys=map.keySet();
2.构造迭代器进行迭代遍历
其中map.get()函数可实现通过填入key值获取value的功能
Set<Integer> keys=map.keySet();
Iterator<Integer> it=keys.iterator();
while(it.hasNext()){
Integer key=it.next();
String value=map.get(key);
System.out.println(key+"="+value);
}
②增强for循环(foreach)
Set<Integer> keys=map.keySet();
for(Integer key:keys){
System.out.println(key+"="+map.get(key));
}
遍历方式2
①迭代器
1.将Map集合转换为Set集合
Set<Map.Entry<Integer,String>> set=map.entrySet();
2.构造迭代器进行迭代遍历
Set<Map.Entry<Integer,String>> set=map.entrySet();
Iterator<Map.Entry<Integer,String>> it2=set.iterator();
while (it2.hasNext()){
Map.Entry<Integer,String> node=it2.next();
Integer key=node.getKey();
String value=node.getValue();
System.out.println(key+"="+value);
}
②增强for循环(foreach)
Set<Map.Entry<Integer,String>> set=map.entrySet();
for(Map.Entry<Integer,String> node:set){
System.out.println(node.getKey()+"="+node.getValue());
}