Stream实现List和Map互转总结
发布人:shili8
发布时间:2025-01-20 16:29
阅读次数:0
**Stream 实现 List 和 Map互转总结**
在 Java 中,Stream 是一种高级 API,用来处理数据流。它提供了许多便捷的方法,让我们可以轻松地实现各种数据操作,如过滤、映射、聚合等。在本文中,我们将讨论如何使用 Stream 实现 List 和 Map 之间的互转。
### **List 到 Map**
首先,我们来看看如何从 List 转换到 Map。假设我们有一个 List,包含一些 Person 对象,每个对象都有 id 和 name 属性。
javaimport java.util.ArrayList;
import java.util.List;
public class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add(new Person(1, "John"));
list.add(new Person(2, "Alice"));
list.add(new Person(3, "Bob"));
// 将 List 转换为 Map Map map = list.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(map);
}
}
在上面的代码中,我们使用 `stream()` 方法将 List 转换为 Stream,然后使用 `collect()` 方法将 Stream 转换为 Map。我们传递了两个函数作为参数:`Person::getId` 和 `Person::getName`,分别用于获取 Person 对象的 id 和 name 属性。
### **Map 到 List**
接下来,我们来看看如何从 Map 转换到 List。假设我们有一个 Map,包含一些 Person 对象,每个对象都有 id 和 name 属性。
javaimport java.util.ArrayList;
import java.util.List;
public class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put(1, "John");
map.put(2, "Alice");
map.put(3, "Bob");
// 将 Map 转换为 List List list = map.entrySet().stream()
.map(entry -> new Person(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
System.out.println(list);
}
}
在上面的代码中,我们使用 `entrySet()` 方法将 Map 的条目转换为 Stream,然后使用 `map()` 方法将每个条目转换为 Person 对象。最后,我们使用 `collect()` 方法将 Stream 转换为 List。
### **总结**
在本文中,我们讨论了如何使用 Stream 实现 List 和 Map 之间的互转。我们展示了从 List 到 Map 的例子,以及从 Map 到 List 的例子。这些例子都使用了 Java8 中提供的 Stream API,包括 `stream()`、`collect()`、`map()` 等方法。
通过阅读本文,你应该能够轻松地实现 List 和 Map 之间的互转,并且理解 Stream API 的基本概念和使用方法。

