Map读取键值对,Java遍历Map的两种实现方法
第一种方法是根据map的keyset()方法来获取key的set集合,然后遍历map取得value的值
import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class HashMapTest2 { public static void main(String[] args) { HashMap map = new HashMap(); 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来获取:
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class HashMapTest4 { public static void main(String[] args) { HashMap map = new HashMap(); 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大小方法:
public static void main(String[] args) { Map map = new HashMap(); map.put("apple", "新鲜的苹果"); //向列表中添加数据 map.put("computer", "配置优良的计算机"); //向列表中添加数据 map.put("book", "堆积成山的图书"); //向列表中添加数据 System.out.println("Map集合大小为:"+map.size()); }
时间: 2024-10-12 16:08:34