Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java collectors.tomap

作者:风外听竹   发布日期:2025-10-16   浏览:18

import java.util.*;
import java.util.stream.Collectors;

public class CollectorsToMapExample {
    public static void main(String[] args) {
        // 创建一个包含多个 Person 对象的列表
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        );

        // 使用 Collectors.toMap 将 List 转换为 Map
        // key 是人的名字,value 是对应的 Person 对象
        Map<String, Person> personMap = people.stream()
            .collect(Collectors.toMap(Person::getName, person -> person));

        // 打印生成的 Map
        personMap.forEach((key, value) -> System.out.println(key + " : " + value));
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

解释说明:

  1. 创建列表:我们首先创建了一个包含多个 Person 对象的列表。
  2. 转换为 Map:使用 Collectors.toMap 方法将 List<Person> 转换为 Map<String, Person>。其中,Person::getName 表示将 Person 对象的名字作为键,person -> person 表示将 Person 对象本身作为值。
  3. 打印结果:最后,我们遍历并打印生成的 Map,以验证转换是否成功。

这个例子展示了如何使用 Collectors.toMap 将一个集合中的元素映射到一个新的 Map 中。

上一篇:java获取当前路径

下一篇:java public

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站