Map集合遍历

Map集合遍历的两种方式:

方式一:使用Map集合的方法keySet()

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class DemoKeySet {
    
    public static void main(String[] args) {
        Map<String, Integer> map=new HashMap<String, Integer>();
        map.put("aa", 151);
        map.put("bb", 161);
        map.put("cc", 168);
        
        //1.使用Map集合的方法keySet(),把Map集合中的key取出来,存储到一个Set集合中
        Set<String> set=map.keySet();
        
        //2.遍历Set集合,获取Map集合中的每一个key
        //使用迭代器遍历set
        Iterator<String> it1=set.iterator();
        while(it1.hasNext()) {
            String key=it1.next();
            //3.通过Map集合中的方法get(key),通过key找到value
            Integer value=map.get(key);
            System.out.println(key+"="+value);
        }
        System.out.println("--------------------");
        
        //使用增强for遍历set
        for(String key:set) {
            Integer value=map.get(key);
            System.out.println(key+"="+value);
        }    
    }
}

方式二:使用Map集合的方法entrySet()

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/*
 * 1.使用Map集合的方法entrySet(),把Map集合中多个Entry对象取出来,存储到一个Set集合中
 * 2.遍历Set集合,获取每一个Entry对象
 * 3.使用Entry对象中的方法getKey()和getValue()获取键与值
 * */
public class DemoEntrySet {

    public static void main(String[] args) {
        Map<String, Integer> map=new HashMap<String, Integer>();
        map.put("aa", 151);
        map.put("bb", 161);
        map.put("cc", 168);
        
        //1.使用Map集合的方法entrySet(),把Map集合中多个Entry对象取出来,存储到一个Set集合中
        Set<Map.Entry<String, Integer>> set=map.entrySet();
        
        //2.遍历Set集合,获取每一个Entry对象
        //使用迭代器
        Iterator<Map.Entry<String, Integer>> it1=set.iterator();
        while(it1.hasNext()) {
            Map.Entry<String, Integer> entry=it1.next();
            //3.使用Entry对象中的方法getKey()和getValue()获取键与值
            String key=entry.getKey();
            Integer value=entry.getValue();
            System.out.println(key+"="+value);
        }
        System.out.println("--------------------------");
        //使用增强for循环
        for(Map.Entry<String, Integer> entry:set) {
            String key=entry.getKey();
            Integer value=entry.getValue();
            System.out.println(key+"="+value);
        }
    }
}
原文地址:https://www.cnblogs.com/svipero/p/11637060.html