Collectors.toMap
时间: 2023-06-10 20:06:26 浏览: 69
Collectors.toMap 是 Java 8 中的一个静态方法,用于将 Stream 中的元素映射为一个 Map 对象。其语法如下:
```java
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper)
```
其中,keyMapper 和 valueMapper 分别是两个函数式接口,用于将 Stream 中的元素映射为 Map 的键和值。例如,假设我们有一个 List<Student>,其中 Student 对象包含 id 和 name 两个属性,我们可以使用 toMap 方法将其转换为一个以 id 为键,以 name 为值的 Map 对象:
```java
List<Student> students = Arrays.asList(
new Student(1, "Tom"),
new Student(2, "Jerry"),
new Student(3, "Alice")
);
Map<Integer, String> studentMap = students.stream()
.collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(studentMap); // 输出 {1=Tom, 2=Jerry, 3=Alice}
```
需要注意的是,如果 Stream 中存在重复的键,toMap 方法会抛出 IllegalStateException 异常。为了避免这种情况,我们可以使用 toMap 方法的重载版本,指定一个合并函数来解决冲突:
```java
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction)
```
例如,假设我们有一个 List<Student>,其中 Student 对象包含 id 和 name 两个属性,我们可以使用 toMap 方法将其转换为一个以 id 为键,以 name 为值的 Map 对象,并在出现重复键时选择后面的值:
```java
List<Student> students = Arrays.asList(
new Student(1, "Tom"),
new Student(2, "Jerry"),
new Student(3, "Alice"),
new Student(3, "Bob")
);
Map<Integer, String> studentMap = students.stream()
.collect(Collectors.toMap(Student::getId, Student::getName, (v1, v2) -> v2));
System.out.println(studentMap); // 输出 {1=Tom, 2=Jerry, 3=Bob}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)