Java 8中List与Map的转换
在Java 8中,我们可以使用Stream API来对集合进行各种操作,包括转换。在这篇文章中,我们将介绍如何在List和Map之间进行转换,并给出相应的代码示例。
List转换为Map
首先,我们来看一下如何将List转换为Map。假设我们有一个存储了学生信息的List,其中每个学生对象包含学生的姓名和年龄。我们希望将这个List转换为一个Map,其中Key为姓名,Value为年龄。
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMapExample {
public static void main(String[] args) {
// 创建一个学生列表
List<Student> students = List.of(
new Student("Alice", 18),
new Student("Bob", 20),
new Student("Charlie", 19)
);
// 转换为Map
Map<String, Integer> studentMap = students.stream()
.collect(Collectors.toMap(Student::getName, Student::getAge));
// 打印结果
studentMap.forEach((name, age) -> System.out.println(name + " -> " + age));
}
static class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
上述代码中,我们使用stream()
方法将List转换为一个Stream对象,然后使用collect()
方法结合Collectors.toMap()
方法将Stream转换为Map。toMap()
方法接受两个参数,第一个参数是Key的提取函数,第二个参数是Value的提取函数。
在这个例子中,我们使用Student::getName
作为Key的提取函数,Student::getAge
作为Value的提取函数。最后,我们使用forEach()
方法遍历Map并打印结果。
Map转换为List
接下来,我们来看一下如何将Map转换为List。假设我们有一个存储了商品信息的Map,其中Key为商品的名称,Value为商品的价格。我们希望将这个Map转换为一个List,其中每个商品对象包含商品的名称和价格。
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MapToListExample {
public static void main(String[] args) {
// 创建一个商品信息的Map
Map<String, Double> products = Map.of(
"Apple", 2.0,
"Banana", 1.5,
"Orange", 3.0
);
// 转换为List
List<Product> productList = products.entrySet().stream()
.map(entry -> new Product(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
// 打印结果
productList.forEach(product -> System.out.println(product.getName() + " -> " + product.getPrice()));
}
static class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
}
在上述代码中,我们使用entrySet()
方法获取Map的Entry对象集合,并使用stream()
方法将其转换为一个Stream对象。然后,我们使用map()
方法将每个Entry对象转换为一个Product对象。最后,我们使用collect()
方法结合Collectors.toList()
方法将Stream转换为List。
总结
在Java 8中,我们可以使用Stream API轻松地在List和Map之间进行转换。通过使用stream()
方法结合collect()
方法和相应的Collector
,我们可以实现各种转换操作。在本文中,我们介绍了如何将List转换为Map以及如何将Map转换为List,并给出了相应的代码示例。
希望本文能够帮助你了解Java 8中List与Map的转换,并在日常开发中使用Stream API更加灵活地处理集合数据。
状态图如下所示:
stateDiagram
[*] --> ListToMapExample
ListToMapExample --> Student
ListToMapExample --> Stream
Stream --> Collectors.toMap
Collectors.toMap --> Student::getName
Collectors.toMap --> Student