Java中Map循环遍历的方法有以下几种:
Map<K, V> map = new HashMap<>();
for (Map.Entry<K, V> entry : map.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
// 进行操作
}
Map<K, V> map = new HashMap<>();
for (K key : map.keySet()) {
V value = map.get(key);
// 进行操作
}
Map<K, V> map = new HashMap<>();
Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<K, V> entry = iterator.next();
K key = entry.getKey();
V value = entry.getValue();
// 进行操作
}
Map<K, V> map = new HashMap<>();
map.forEach((key, value) -> {
// 进行操作
});
其中,方法1和方法2是较常用的遍历方法,方法3适用于需要在遍历过程中删除元素的场景,方法4是一种简洁的写法。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:map循环遍历的方法有哪些几种