首先初始化一个全局 map

public static Map<String, String> map = new HashMap<String, String>() {
    private static final long serialVersionUID = 1L;
        {
            put("name", "test");
            put("gender", "man");
            put("country", "China");
        }
}
@BeforeClass
public void initMap() {
    System.out.println(map);    // {country=China, gender=man, name=test}
}
@AfterClass
public void clearMap() {
    map.clear();
    System.out.println(map);    // {}
}

遍历 keySet

@Test
public readKeys() {
    System.out.println(map.keySet());   // [country, gender, name]
    for(String key : map.keySet()) {
        System.out.println(key + ":" + map.get(key));
        // country:China
        // gender:man
        // name:test
    }
}

遍历 values

@Test
public readValues() {
    System.out.println(map.values());   // [China, man, test]
    for(String val : map.values()) {
        System.out.println(val);
        // China
        // man
        // test
    }
}

遍历 entrySet (iterator遍历)

@Test
public readEntrys() {
    System.out.println(map.entrySet());   // [country=China, gender=man, name=test]
    Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry<String, String> entry = it.next();
        System.out.println(entry.getKey() + ":" + entry.getValue());
        // country:China
        // gender:man
        // name:test

        //it.remove();
    }
}

forEach 结合 Lambda(需java8以上) 遍历 key,value

@Test
public readLambda() {
    map.forEach((key, value) -> {
        System.out.println(key + ":" + value);
        // country:China
        // gender:man
        // name:test
    });
}

操作建议

  • 单纯获取key或者value,推荐使用keySe/values
  • 获取entry推荐使用entrySet
  • 遍历过程中需要删除元素推荐使用Iterator
  • 遍历过程中增加元素,可以新建一个临时map存放新增的元素,等遍历完毕,再把临时map放到原来的map中
02-11 15:34