Java中Map集合遍历方式,keySet()方法

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

/*

  • Map集合的遍历

  • 利用键获取值

  • Map接口中定义fangfakeySet

  • 所有的键,存储到Set集合

  • */

     public class MapDemo1 {
     	public static void main(String[] args) {
     		/*
     		 * 1,调用map集合方法中的keySet,所有的键存储到Set集合中 
     		 * 2,遍历Set集合,获取Set集合中所有的元素(就是Map的键)
     		 * 3,调用map集合方法get
     		 */
     		function(); 
     	}
    

    public static void function() {
    Map map = new HashMap();
    map.put(“a”, 1);
    map.put(“b”, 2);
    map.put(“c”, 3);
    // 1,调用map集合方法中的keySet,所有的键存储到Set集合中
    Set set = map.keySet();
    // 2,遍历Set集合,获取Set集合中所有的元素(就是Map的键)
    Iterator it = set.iterator();
    while (it.hasNext()) {
    // 3,调用map集合方法get
    String key = it.next();// it.next()返回的是set集合元素,也就是map中的键
    Integer value = map.get(key);
    System.out.println(key + “=” + value);
    }
    }
    }

你可能感兴趣的:(Java高级)