JSRUN 用代码说话

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闪电教程系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的闪电教程,让知识的积累变得统一完整、自成体系。 大家可以一起参与进共编,让零散的知识点帮助更多的人。
X
支付宝
9.99
无法付款,请点击这里
金额: 0
备注:
转账时请填写正确的金额和备注信息,到账由人工处理,可能需要较长时间
如有疑问请联系QQ:565830900
正在生成二维码, 此过程可能需要15秒钟