import java.util.*; class Demo { public static void main(String[] args) { Map<String,String> map = new HashMap<String,String>(); map.put("张三","李四"); map.put("文章","马伊利"); map.put("汪峰","章子怡"); /*//遍历方式一:可以使用keySet方法遍历 keySet方法返回的集合只是包含了所有的键,没有包含值。 Set<String> set = map.keySet(); //把map集合中所有key的数据存储到Set集合中返回。 Iterator<String> it = set.iterator(); while(it.hasNext()){ String key = it.next(); System.out.println("键:"+key+" 值:"+map.get(key)); }*/ /*//方式二:使用values方法遍历 values方法返回的对象只是包含了map中的所有值,没有键的数据。 Collection<String> list = map.values();//把map中的所有值存储到一个Collection集合中返回 Iterator<String> it= list.iterator(); while (it.hasNext()){ String value = it.next(); System.out.println("值:"+value); }*/ //方式三:使用Entry 推荐使用 Set<Map.Entry<String,String>> entrys = map.entrySet(); Iterator<Map.Entry<String,String>> it = entrys.iterator(); while(it.hasNext()){ Map.Entry<String,String> entry = it.next(); System.out.println("键:"+entry.getKey()+"值:"+entry.getValue()); } } }
Map中使用Iterator便利集合的几种方式
最新推荐文章于 2024-05-29 11:26:00 发布