Java 8 将List转换为Map

2018-03-27 16:37:57

几个Java 8示例来向您展示如何将一个List对象转换为一个Map,以及如何处理重复的键

Hosting.java

package com.mkyong.java8public class Hosting {
    private int Id;
    private String name;
    private long websites;
    public Hosting(int id, String name, long websites) {
        Id = id;
        this.name = name;
        this.websites = websites;
    }
    //getters, setters and toString()}

List到Map - Collectors.toMap()


创建Hosting对象的List,Collectors.toMap并将其转换为Map。

TestListMap.java

package com.mkyong.java8import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Collectors;public class TestListMap {
    public static void main(String[] args) {
        List<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", 80000));
        list.add(new Hosting(2, "linode.com", 90000));
        list.add(new Hosting(3, "digitalocean.com", 120000));
        list.add(new Hosting(4, "aws.amazon.com", 200000));
        list.add(new Hosting(5, "mkyong.com", 1));
        // key = id, value - websites
        Map<Integer, String> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getId, Hosting::getName));
        System.out.println("Result 1 : " + result1);
        // key = name, value - websites
        Map<String, Long> result2 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites));
        System.out.println("Result 2 : " + result2);
        // Same with result1, just different syntax
        // key = id, value = name
        Map<Integer, String> result3 = list.stream().collect(
                Collectors.toMap(x -> x.getId(), x -> x.getName()));
        System.out.println("Result 3 : " + result3);
    }}

Output

Result 1 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com, 4=aws.amazon.com, 5=mkyong.com}Result 2 : {liquidweb.com=80000, mkyong.com=1, digitalocean.com=120000, aws.amazon.com=200000, linode.com=90000}Result 3 : {1=liquidweb.com, 2=linode.com, 3=digitalocean.com, 4=aws.amazon.com, 5=mkyong.com}

2.列出Map - 重复键

2.1运行下面的代码,重复的关键错误将被抛出!

TestDuplicatedKey.java

package com.mkyong.java8;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Collectors;public class TestDuplicatedKey {
    public static void main(String[] args) {
        List<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", 80000));
        list.add(new Hosting(2, "linode.com", 90000));
        list.add(new Hosting(3, "digitalocean.com", 120000));
        list.add(new Hosting(4, "aws.amazon.com", 200000));
        list.add(new Hosting(5, "mkyong.com", 1));
        list.add(new Hosting(6, "linode.com", 100000)); // new line
        // key = name, value - websites , but the key 'linode' is duplicated!?
        Map<String, Long> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites));
        System.out.println("Result 1 : " + result1);
    }}

输出 - 下面的错误信息有点误导,应该显示“linode”而不是键的值。

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 90000
	at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
	at java.util.HashMap.merge(HashMap.java:1245)
	//...

2.2要解决上述重复的关键问题,请传入第三个mergeFunction参数,如下所示:

Map<String, Long> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites,
                        (oldValue, newValue) -> oldValue                )
        );

Output

Result 1 : {..., aws.amazon.com=200000, linode.com=90000}

3.3尝试newValue

Map<String, Long> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getName, Hosting::getWebsites,
                        (oldValue, newValue) -> newvalue                )
        );

Output

Result 1 : {..., aws.amazon.com=200000, linode.com=100000}

3.列出Map- 排序Collect

TestSortCollect.java

package com.mkyong.java8;import java.util.*;import java.util.stream.Collectors;public class TestSortCollect {
    public static void main(String[] args) {
        List<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", 80000));
        list.add(new Hosting(2, "linode.com", 90000));
        list.add(new Hosting(3, "digitalocean.com", 120000));
        list.add(new Hosting(4, "aws.amazon.com", 200000));
        list.add(new Hosting(5, "mkyong.com", 1));
        list.add(new Hosting(6, "linode.com", 100000));
        //example 1
        Map result1 = list.stream()
                .sorted(Comparator.comparingLong(Hosting::getWebsites).reversed())
                .collect(
                        Collectors.toMap(
                                Hosting::getName, Hosting::getWebsites, // key = name, value = websites
                                (oldValue, newValue) -> oldValue,       // if same key, take the old key
                                LinkedHashMap::new                      // returns a LinkedHashMap, keep order
                        ));
        System.out.println("Result 1 : " + result1);
    }}

Output

Result 1 : {aws.amazon.com=200000, digitalocean.com=120000, linode.com=100000, liquidweb.com=8000
  • 2019-11-09 19:16:35

    java标记过期方法

    java注解:@Deprecated(不建议使用的,废弃的);@SuppressWarnings(忽略警告,达到抑制编译器产生警告的目的)

  • 2019-11-12 02:56:39

    使用.htaccess重定向后无法显示图片,CSS失效,该如何处理

    现在我需要把这个域名泛解析到blog目录(*.mydomain.org),同时保持另外两个目录的解析不变。尝试对最后一段作以下修改后(前面的内容不变),出现问题:另两个目录中的网站内的图片无法显示,CSS全部失效。

  • 2019-11-14 11:21:34

    vue中的this指向问题

    ※ 对于普通函数(包括匿名函数),this指的是直接的调用者,在非严格模式下,如果没有直接调用者,this指的是window。showMessage1()里setTimeout使用了匿名函数,this指向 window。 ※ 箭头函数是没有自己的this,在它内部使用的this是由它定义的宿主对象决定。showMessage2()里定义的箭头函数宿主对象为vue实例,所以它里面使用的this指向vue实例。

  • 2019-11-18 23:18:49

    spring boot中读取配置信息一

    首先我们都知道一个常识,那就是每个人都有自己的年龄,比如我们现在的业务需求是查询所有年龄大于20的人的相关信息,如果我们选择通过配置文件来配置这个值为20的常量的话,我们该如何配置和如何从配置文件中获取这个值呢?,application.yml的内容如下(注意 “age:“ 和 “20“ 之间需要一个空格,yml的语法 ):

  • 2019-11-19 01:20:18

    java8 forEach、filter、map

    filter()、findAny()、orElse()配合使用,可以根据条件获取某个元素,如果没有返回指定的值。