Java 8 – Convert List to Map

package com.mkyong.java8

public 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()
}

1. List to Map – Collectors.toMap()
package com.mkyong.java8

import 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. List to Map – Duplicated Key!
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);

}
}

Output – The error message below is a bit misleading, it should show “linode” instead of the value of the key.

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 To solve the duplicated key issue above, pass in the third mergeFunction argument like this :

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}
Copy
Note
(oldValue, newValue) -> oldValue ==> If the key is duplicated, do you prefer oldKey or newKey?

3.3 Try 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. List to Map – Sort & Collect
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);

}
}

Result 1 : {aws.amazon.com=200000, digitalocean.com=120000, linode.com=100000, liquidweb.com=80000, mkyong.com=1}

http://www.mkyong.com/java8/java-8-convert-list-to-map/

Java 8 – Convert List to Map的更多相关文章

  1. Java 8 – Convert Map to LIST

    Java 8 – Convert Map to LIST Few Java examples to convert a Map to a List Map<String, String> ...

  2. Java 集合系列14之 Map总结(HashMap, Hashtable, TreeMap, WeakHashMap等使用场景)

    概要 学完了Map的全部内容,我们再回头开开Map的框架图. 本章内容包括:第1部分 Map概括第2部分 HashMap和Hashtable异同第3部分 HashMap和WeakHashMap异同 转 ...

  3. 【转】java 容器类使用 Collection,Map,HashMap,hashTable,TreeMap,List,Vector,ArrayList的区别

    原文网址:http://www.360doc.com/content/15/0427/22/1709014_466468021.shtml java 容器类使用 Collection,Map,Hash ...

  4. JAVA基础--容器 Set, List, Map

    Colections接口, Iterator接口, Set接口, List接口, Comparable接口, Map接口 Collections类 容器:装各种对象. 所有容器都在java.util里 ...

  5. Java中集合List,Map和Set的区别

    Java中集合List,Map和Set的区别 1.List和Set的父接口是Collection,而Map不是 2.List中的元素是有序的,可以重复的 3.Map是Key-Value映射关系,且Ke ...

  6. 第51节:Java当中的集合框架Map

    简书作者:达叔小生 Java当中的集合框架Map 01 Map提供了三个集合视图: 键集 值集 键-值 映射集 public String getWeek(int num){ if(num<0 ...

  7. java.util (Collection接口和Map接口)

    1:Collection和Map接口的几个主要继承和实现类                  1.1  Collection接口 Collection是最基本的集合接口,一个Collection代表一 ...

  8. JAVA 中的 Collection 和 Map 以及相关派生类的概念

    JAVA中Collection接口和Map接口的主要实现类   Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的 ...

  9. JAVA中Collection接口和Map接口的主要实现类

    Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements).一些Collection允许相同的元素 ...

随机推荐

  1. 【转】exec xargs的区别 另附eval命令介绍

    -exec:  对符合条件的文件执行所给的Linux 命令,执行exec后面的shell脚本.脚本中,{}表示命令的参数即为所找到的文件,以:表示comman命令的结束.\是转义符,因为分号在命令中还 ...

  2. ES6学习笔记八:类与继承

    一:Class ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板.通过class关键字,可以定义类. 定义“类”的方法的时候,前面不需要加上function这个关键 ...

  3. simplify-path-字符串处理,去除多余路径

    题目描述 Given an absolute path for a file (Unix-style), simplify it. For example,path ="/home/&quo ...

  4. 让服务器可以下载apk和ipa文件

    选中指定网站→在右侧找到 MIME类型 → 双击进入已有类型页 → 点击最右侧添加 apk    application/vnd.android.package-archive MRP文件(国内普遍的 ...

  5. ORA-00942 表或视图不存在

    场景:跨scheme创建视图,提示ORA-00942 表或视图不存在 1. 创建两个用户 CREATE USER ODI_SRC IDENTIFIED BY ODI_SRC CREATE USER O ...

  6. .NET Core 全新认识

    来源:yubinfeng cnblogs.com/yubinfeng/p/6626694.html 一.概述      .NET 经历14年,在Windows平台上的表现已经相当优秀,但是“跨平台.开 ...

  7. java 生成二维码后叠加LOGO并转换成base64

      1.代码 见文末推荐 2.测试 测试1:生成base64码 public static void main(String[] args) throws Exception { String dat ...

  8. kettle的安装、配置与运行

      1.下载与安装 官方下载地址:https://community.hitachivantara.com/docs/DOC-1009855 下载好后,解压,还可以对该目录进行重命名. 2.环境配置 ...

  9. 将Excel表格保存为图片

    如何将Excel表格保存为图片,可参见以下几种方法: 1.借助其它办法软件,例如Word或PPT. 步骤:选中Excel中需要被保存成图片的内容,Ctrl+C进行复制,打开Word或PPT办公软件,鼠 ...

  10. Q值, 电感Q因素, 电感品质因素, Inductor Q, Quality Factor

    Q值基本概念 Q值, 品质因素, Quality Factor 是广泛使用于物理和工程领域的一个参数, 这指的是一个机械或非机械的组件里, 共振(谐振)的能量损失比例, 是衡量一个元件或谐振回路性能的 ...