Map读取键值对,Java遍历Map的两种实现方法
第一种方法是根据map的keyset()方法来获取key的set集合,然后遍历map取得value的值
代码如下 | 复制代码 |
importjava.util.HashMap; importjava.util.Iterator; importjava.util.Set; publicclassHashMapTest2 { publicstaticvoidmain(String[] args) { HashMap map =newHashMap();
map.put("a","aaaa"); map.put("b","bbbb"); map.put("c","cccc"); map.put("d","dddd");
Set set = map.keySet();
for(Iterator iter = set.iterator(); iter.hasNext();) { String key = (String)iter.next(); String value = (String)map.get(key); System.out.println(key+"===="+value); } } } |
第二种方式是使用Map.Entry来获取:
代码如下 | 复制代码 |
importjava.util.HashMap; importjava.util.Iterator; importjava.util.Map; importjava.util.Set; publicclassHashMapTest4 { publicstaticvoidmain(String[] args) { HashMap map =newHashMap();
map.put("a","aa"); map.put("b","bb"); map.put("c","cc"); map.put("d","dd");
Set set = map.entrySet();
for(Iterator iter = set.iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next();
String key = (String)entry.getKey(); String value = (String)entry.getValue(); System.out.println(key +" :"+ value); } } } |
获取Map大小方法:
代码如下 | 复制代码 |
publicstaticvoidmain(String[] args) {
Map map =newHashMap();
map.put("apple","新鲜的苹果"); //向列表中添加数据
map.put("computer","配置优良的计算机"); //向列表中添加数据
map.put("book","堆积成山的图书"); //向列表中添加数据
System.out.println("Map集合大小为:"+map.size());
} |
SpringBoot测试配置属性与web启动环境解析
vue中将el-switch值true、false改为number类型的1和0解析
Vue中的路由配置项meta使用解读
SpringBoot自定义bean绑定解析
SpringBoot常用计量与bean属性校验和进制数据转换规则解析
工厂方法在Spring框架中的运用介绍