map集合中的键值对对象遍历

package com.day15.Map;

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

/*
* map集合中的第二种遍历方式
*/
public class MapFour {

  public static void main(String[] args) {
    Map<String, Integer> ma=new HashMap<>();
    ma.put("Kobe",20);
    ma.put("KG",21);
    ma.put("PP",22);
    ma.put("Allen",23);
    //Map.Entry说明Entry是Map的内部接口,将键和值封装成了Entry对象,并存储在Set集合中
    Set<Map.Entry<String,Integer>> es=ma.entrySet();
    //获取每一个对象
    Iterator<Map.Entry<String,Integer>> it=es.iterator();
    while(it.hasNext()) {
      Map.Entry<String, Integer> en=it.next();
      String key=en.getKey();
      Integer value=en.getValue();
      System.out.print(key+"="+value);//PP=22Kobe=20KG=21Allen=23
    }
  }

}

猜你喜欢

转载自www.cnblogs.com/zhujialei123/p/9033893.html