JSRUN 用代码说话
JSRUN.NET
保存开源代码和笔记 永久免费

Java 8 – 将Map转成List

编辑教程

A Java 8 example to convert a List<?> of objects into a Map<k, v>

1. POJO example

Hosting.java

package com.mkyong.java8

import java.util.Date;

public class Hosting {

    private int Id;
    private String name;
    private Date createdDate;

    public Hosting(int id, String name, Date createdDate) {
        Id = id;
        this.name = name;
        this.createdDate = createdDate;
    }

    //getters and setters
}

2. Java 8 – Collectors.toMap()

Example to convert a List into a stream, then collect it with Collectors.toMap

TestJava8.java

package com.mkyong.java8

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TestJava8 {

    public static void main(String[] args) {

        List<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", new Date()));
        list.add(new Hosting(2, "linode.com", new Date()));
        list.add(new Hosting(3, "digitalocean.com", new Date()));

        //example 1
        Map<Integer, String> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getId, Hosting::getName));

        System.out.println("Result 1 : " + result1);

        //example 2
        Map<Integer, String> result2 = list.stream().collect(
                Collectors.toMap(x -> x.getId(), x -> x.getName()));

        System.out.println("Result 2 : " + result2);

    }

}

Output

Result 1 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com}
Result 2 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com}

References

  1. Java 8 Collectors JavaDoc

如果觉得JSRUN的教程对您有用,请随意打赏。您的支持将鼓励JSRUN继续提供更好的服务

赞助JSRUN
JSRUN闪电教程系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的闪电教程,让知识的积累变得统一完整、自成体系。 大家可以一起参与进共编,让零散的知识点帮助更多的人。
X
支付宝
9.99
无法付款,请点击这里
如遇到支付问题请联系QQ:565830900
正在生成二维码, 此过程可能需要15秒钟
谢谢支持,我一定会更加努力的