package com.tang.chapter6.map; import java.util.HashMap; import java.util.Map; /** * @author Tang */ public class Demo01 { public static void main(String[] args) { Map<String,String> map = new HashMap<String, String>(); map.put("1","zs"); map.put("2","ls"); map.put("3","ww"); map.put("4","ll"); System.out.println("Map集合" + map); System.out.println("是否包含键对象1:" + map.containsKey("1")); System.out.println("是否包含值对象zs:" + map.containsValue("zs")); System.out.println("获取所有的键对象:" + map.keySet()); System.out.println("获取所有的值对象:" + map.values()); System.out.println("获取键对象1的值:" + map.get("1")); map.replace("1","hello world"); System.out.println("修改键对象1的值:" + map.get("1") ); System.out.println(map); System.out.println("删除键对象1的值:" + map.remove("1")); System.out.println(map); } }
使用迭代器遍历
public class Demo01 { public static void main(String[] args) { Map<String,String> map = new HashMap<String, String>(); map.put("1","zs"); map.put("2","ls"); map.put("3","ww"); map.put("4","ll"); System.out.println(map); Set<String> keySet = map.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()){ Object key = iterator.next(); Object value = map.get(key); System.out.println(key + ":" + value); } } }
public class Demo01 { public static void main(String[] args) { Map<String,String> map = new HashMap<String, String>(); map.put("1","zs"); map.put("2","ls"); map.put("3","ww"); map.put("4","ll"); System.out.println(map); Set<Map.Entry<String, String>> entrySet = map.entrySet(); Iterator<Map.Entry<String, String>> iterator = entrySet.iterator(); while (iterator.hasNext()){ Map.Entry entry = (Map.Entry)(iterator.next()); Object key = entry.getKey(); Object value = entry.getValue(); System.out.println(key+":"+value); } }
说明一点:EntrySet方法比KeySet方法要快一点
使用foreach方法遍历集合
public class Demo01 { public static void main(String[] args) { Map<String,String> map = new HashMap<String, String>(); map.put("1","zs"); map.put("2","ls"); map.put("3","ww"); map.put("4","ll"); System.out.println(map); map.forEach((key,value) -> System.out.println(key+ ":" +value)); // 遍历集合的Value值 Collection<String> values = map.values(); values.forEach(System.out::println); } }