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
  • 2021-01-16 09:39:32

    iOS 更改状态栏、导航栏颜色,电池颜色

    注意事项,两种方法设置View controller-based status bar appearance 的值不一样,并且如果你的plist里面没有View controller-based status bar appearance,你需要新建一个。然后就可以成功了。

  • 2021-01-16 09:45:19

    tabbar的titlePositionAdjustment设置文字距离

    指定相应的数据去偏移一个位置,向右或者向下为正值,向左或者向上为负值,不过首先你得有一个相对位置的坐标。而tabbarItem文字的坐标是底部为x轴,y轴则是tabbarItem的centerX;

  • 2021-01-16 09:49:13

    Cocoapods如何查看项目中引入库的版本号

    项目中已经安装过Cocoapods,并生成了Podfile.lock文件。 打开终端,cd命令切换到项目中的Podfile.lock文件目录下,执行命令:cat Podfile.lock 即可。也可以用文本方式打开 Podfile.lock 文件。示例如下:

  • 2021-01-18 13:50:21

    vue实现粘贴功能

    paste事件就是粘贴事件 需要通过clipboardData获得粘贴的内容