Java 如何将 List 转换为 MAP

有时候我们需要将给定的 List 转换为 Map。

如果你使用的是 Java 8 以后版本的话,Stream 是你的好朋友。

Java 8 map example 2

Java 8

 public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
    Map<Integer, Animal> map = list.stream()
      .collect(Collectors.toMap(Animal::getId, Function.identity()));
    return map;
}

上面的代码可以非常容易的完成转换,我们有一个 Animal 对象的 List。

上面的代码将会把 Id 作为 Key,然后生成的 Map 是以 id 为 Key,Animal 为Value 的 Map。

Guava

如果使用 Guava 就更加简单了。

public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
    Map<Integer, Animal> map = Maps
      .uniqueIndex(list, Animal::getId);
    return map;
}

使用 Maps 的工具类就可以了,这个工具类可以直接用。

更进一步

如果对需要生成的 Map 进行处理。

Key 是对象中的一个值,Value 是 List 对象中的另外一个值。

例如可以使用下面的代码:

listingStatusList.stream().collect(Collectors.toMap(CListingStatus::getListingStatusKey, CListingStatus::getListingStatus));

其中 CListingStatus 对象是这样定义的。

@Entity
@Getter
@Setter
public class CListingStatus extends AbstractPersistable<Long> {

    @ManyToOne
    @JoinColumn(name = "rets_id", nullable = false)
    private ConfRets confRets;

    private String listingStatusKey;

    private ListingStatus listingStatus ;

}

对 Map 中的对象设值

针对 Stream 中的对象,我们可能还需要重新设置为其他的对象。

这个时候我们就可以使用 lambda 函数了。

同样的代码:

        HashMap<String, Agent> agentHashMap = (HashMap) mlsAgentList.stream().collect(Collectors.toMap(MlsAgent::getMlsAgentId, mlsAgent -> {
            Agent agent = new Agent();
            agent.setAgentId(mlsAgent.getMlsAgentId());
            agent.setAgentNameFirst(mlsAgent.getNameFirst());
            agent.setAgentNameLast(mlsAgent.getNameLast());
            agent.setAgentEmail(mlsAgent.getEmail());
            return agent;
        }));

我们返回的 Map 使用了一个新的对象为 Value。

上面针对 Stream 转换为 Map 的方法进行了一些小总结,这些方法可能实际编程的时候使用的频率比较高。

同时能够避免大量使用 For 循环的情况。

Stream 还是需要好好了解下的。

 

https://www.ossez.com/t/java-list-map/14144

posted @   huyuchengus  阅读(2443)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
历史上的今天:
2020-10-12 Junit-jupiter-api 和 junit-jupiter-engine 的区别是什么
2020-10-12 Maven 依赖中的 dependencies 和 dependencyManagement
2019-10-12 Gradle 的项目导入到 IntelliJ 后子项目源代码不能导入
2019-10-12 在 CentOS 7 上安装 RabbitMQ
点击右上角即可分享
微信分享提示