获取map集合中的键和值

//此处建议遍历集合使用迭代器,如果使用for循环的话,获取数据可以,要是remove数据的话会有意想不到的想过。。。。。个人强烈建议迭代器遍历 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Main{
 public static void main(String[] args) {
  // 创建map集合对象
  Map<String, Integer> maps = new HashMap<String, Integer>();
  // 向集合对象中添加元素
  maps.put("gss01", 01);
  maps.put("gss02", 02);
  mapKeyToValue(maps);
  mapEntry(maps);
 }
 /**
  * show 根据map的键找值
  *
  * @param map
  */
 public static void mapKeyToValue(Map<String, Integer> maps) {
  Set<String> keySet = maps.keySet();
  Iterator<String> iterator = keySet.iterator();
  while (iterator.hasNext()) {
   String next = iterator.next();
   System.out.println("根据map的键找值,map中的键值对为:");
   System.out.println(next+"--->"+maps.get(next));
  }
 }
 /**
  * show 根据键值对象获取键和值
  * @param maps
  */
 public static void mapEntry(Map<String, Integer> maps){
  Set<Entry<String,Integer>> entrySet = maps.entrySet();
  Iterator<Entry<String, Integer>> iterator = entrySet.iterator();
  while(iterator.hasNext()){
   Entry<String, Integer> next = iterator.next();
   System.out.println("根据键值对象获取键和值,map中的键值对为:");
   System.out.println(next.getKey()+"--->"+next.getValue());
  }
 }
}
posted @ 2020-08-19 14:48  Be_Ready_For_Battle  阅读(264)  评论(0)    收藏  举报