【Java】Java遍历Map方法合集
admin2025-12-28 19:08:33【世界杯比赛赛】
前言在Java中,Map 是一个接口,它存储键值对(key-value pairs)。遍历 Map 可以通过多种方式完成,本文中洲洲将介绍一些常见的遍历 Map 的方法
方法一:使用 entrySet() 方法entrySet() 返回的是一个 Set 集合,集合中的元素是 Map.Entry 对象,每个对象都包含键和值。
代码语言:javascript复制Map
for (Map.Entry
K key = entry.getKey();
V value = entry.getValue();
System.out.println(key + " : " + value);
}方法二:使用 keySet() 方法keySet() 返回的是一个 Set 集合,包含所有键。如果你只需要遍历键,可以使用这个方法。
代码语言:javascript复制Map
for (K key : map.keySet()) {
V value = map.get(key);
System.out.println(key + " : " + value);
}方法三:使用 values() 方法values() 返回的是一个 Collection 集合,包含所有值。如果你只需要遍历值,可以使用这个方法。
代码语言:javascript复制Map
for (V value : map.values()) {
System.out.println(value);
}方法四:使用 Java 8 的 forEach() 方法Java 8 引入了新的 forEach() 方法,它接受一个 BiConsumer 函数式接口,可以对每个键值对执行操作。
代码语言:javascript复制Map
map.forEach((key, value) -> {
System.out.println(key + " : " + value);
});方法五:使用 Java 8 的 stream() 方法Java 8 还引入了 stream() 方法,可以对 Map 进行更复杂的操作,如过滤、映射等。
代码语言:javascript复制Map
map.entrySet().stream()
.filter(entry -> /* 条件 */)
.forEach(entry -> {
K key = entry.getKey();
V value = entry.getValue();
System.out.println(key + " : " + value);
});方法六:使用 Iterator使用 Iterator 遍历 Map,可以手动控制遍历过程,包括安全地删除元素。
代码语言:javascript复制Map
Iterator
while (iterator.hasNext()) {
Map.Entry
K key = entry.getKey();
V value = entry.getValue();
System.out.println(key + " : " + value);
// 如果需要删除元素
// iterator.remove();
}方法七:lambda表达式代码语言:javascript复制 map.forEach((key,value)->{
System.out.println(key);
System.out.println(value);
});List转换Map代码语言:javascript复制/**
* 转换Map,保存后者
* @return Map
*/
private static Map
List
bookList.add(new Book("The King","Tom","1955"));
bookList.add(new Book("The King Tail","Jack","1956"));
bookList.add(new Book("The King Tail","Bean","1957"));
bookList.add(new Book("The King Help","Bean","1957"));
// 注意Key值重复时处理,这里是保存旧的值,之前加入的数据
// Function super T, ? extends K> keyMapper
// Function super T, ? extends U> valueMapper->Function.identity()
// BinaryOperator mergeFunction
return bookList.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(),(oldValue,newValue)->oldValue));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Book{
private String name;
private String author;
private String releaseYear;
}