java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java中List转换成Map方式

Java中List转换成Map的两种实现方式

作者:我需要打球

Java中List转Map常用Stream API,通过collect(Collectors.toMap())实现,需明确键值规则并处理重复键冲突,支持灵活扩展

在 Java 中,将List转换为Map是常见操作,通常需要指定Map的键(Key)和值(Value),常用工具类有Java 8 Stream API

一、Java8 Stream API

package list2map;

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

// 定义实体类
class User {
    private Long id;
    private String name;
    
    // 构造函数、getter、setter省略
    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    public Long getId() { return id; }
    public String getName() { return name; }
}

public class ListToMapExample {
    public static void main(String[] args) {
        // 准备List数据
        List<User> userList = List.of(
            new User(1L, "Alice"),
            new User(2L, "Bob"),
//            new User(1L, "Bob"),如果两个id都是1,那么Bob会覆盖Alice
            new User(3L, "Charlie")
        );
        // 转换为Map<id, User>
        Map<Long, User> userMap = userList.stream()
            .collect(Collectors.toMap(
                User::getId,  // 键:User对象的id
                user -> user,   // 值:User对象本身
                    (oldValue,newValue) -> newValue, //冲突时取新值
                    TreeMap::new //指定Map的实现类

            ));
        //Map集合的遍历
        Set<Map.Entry<Long, User>> entries = userMap.entrySet();
        for (Map.Entry<Long, User> entry : entries) {
            System.out.println("entry.getKey() = " + entry.getKey());
            System.out.println("entry.getValue() = " + entry.getValue().getName());
        }
    }
}

二、传统方式

import java.util.HashMap;
import java.util.Map;

Map<Long, User> userMap = new HashMap<>();
for (User user : userList) {
    userMap.put(user.getId(), user);  // 手动put键值对
}

三、总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文