package com.chen.test.Demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class DomeHashMap {
private static Logger log = LoggerFactory.getLogger(DomeHashMap.class);
/**
* Map输出方法1
* @uesful: 利用keySet()方法获取key,根据key获取value
* @param map
*/
public static void hashMapPrint1(Map<String,Integer> map){
Set<String> keySet = map.keySet();
for (String key : keySet){
Integer value = map.get(key);
log.info("key: " + key + "value: " + value);
}
}
/**
* Map输出方法2
* @uesful: 使用Map中entrySet()中iterator()方法,通过iterator.next()获取键值对,
* 使用iterator需要注意的,在循环体中先创建iterator.next()对象,然后在获取对应的key和value
* 《错误使用的》在循环体内不可使用iterator.next.getKey()获取key,iterator.next.getValue()获取value 使用了两次next()
* @param map
*/
public static void hashMapPrint2(Map<String,Integer> map){
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, Integer> next = iterator.next();
String key = next.getKey();
Integer value = next.getValue();
log.info("key: " + key + "value: " + value);
}
}
/**
* Map输出方法3 《推荐使用该方法》
* @useful: 使用Map中entrySet()方法获取key和value
* @param map
*/
public static void hashMapPrint3(Map<String, Integer> map){
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String,Integer> entry: entries){
String key = entry.getKey();
Integer value = entry.getValue();
log.info("Key: " + key + "value: " + value);
}
}
/**
* Map输出方法4
* @useful: 仅仅输出value值,可以使用map.values()方法
* @param map
*/
public static void hashMapPrint4(Map<String,Integer> map){
Collection<Integer> values = map.values();
for (Integer value : values){
log.info("getValue: " + value);
}
}
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put("key"+ i,i);
}
log.info("Map输出方法1");
hashMapPrint1(map);
log.info("Map输出方法2");
hashMapPrint2(map);
log.info("Map输出方法3");
hashMapPrint3(map);
log.info("Map输出方法4,仅输出value值");
hashMapPrint4(map);
}
}