java hashmap的几种遍历方法

hashmap的遍历经常会碰到,并且会经常记不住,以下是baidu AI提供的几种方法。

1、使用for-each循环和Map.Entry

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
 
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

2、使用for-each循环和keySet()

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
 
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key + ", Value = " + map.get(key));
}

3、使用for-each循环和values()

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
 
for (String value : map.values()) {
    System.out.println("Value = " + value);
}

4、使用Iterator(Iterator<Map.Entry<Integer, String>>)

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
 
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<Integer, String> entry = iterator.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

5、使用Java 8的Stream API (如果你使用的是Java 8或更高版本)

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
 
map.forEach((key, value) -> System.out.println("Key = " + key + ", Value = " + value));

场景说明:有一个数据copy的需求,需要修改原始的groupid为new groupid

实际测试:

HashMap<Integer, Integer> keys = new HashMap<Integer, Integer>();
keys.forEach((key, value) -> {
							if (entry.getGroupid().intValue() == key.intValue()) {
								entry.setGroupid(value);
							}
						});

这种方法看上去比较简单明了,而且好记。。。

猜你喜欢

转载自blog.csdn.net/jwbabc/article/details/143369113