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. 【推荐】ImageProcessor.Web,再也不用自己生成缩略图了

    1.什么是ImageProcessor.Web ImageProcessor.Web是基于ImageProcessor的web图像处理模块,允许开发者使用URL查询字符串参数的方式作为指令执行图像处理 ...

  2. tornado code

    # get the requtest URL self.request.uri

  3. CentOS7系统安装Nginx进行跨域处理

    1 打开终端 依次输入以下命令: yum install nginx vi /etc/nginx/nginx.conf 然后编辑修改该文件中代码,以下是修改后的代码全文: # For more inf ...

  4. stopPropagation 和stopImmediatePropagation区别

    1.示例代码 <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UT ...

  5. 来自Unix/Linux的编程启发录

    本篇文章已授权微信公众号 guolin_blog (郭霖)独家公布重点内容 2017年第一篇文章,祝各位好友新年快乐. 年前因为不小心坐到了自己左手大拇指导致轻微的骨裂,没有按时更新,实在是羞愧.今年 ...

  6. 如何捕获 System.loadLibrary 产生的异常?(转)

    如何捕获 System.loadLibrary 产生的异常? 当使用以下代码时,会发现异常处理的代码根本不会被执行: try{ System.loadLibrary("SimpleAuthe ...

  7. 【Linux】将一个命令的输出发送给另外一个命令

    一个命令的输出可以作为下一个命令的输入,下一个命令的输出又会传递给下一个命令 我们通常使用管道和子shell的方法来组合多个命令的输出 格式 $ cmd1 |cmd2 | cmd3 这里的3个组合命令 ...

  8. Spark -14:spark Hadoop 高可用模式下读写hdfs

    第一种,通过配置文件 val sc = new SparkContext() sc.hadoopConfiguration.set("fs.defaultFS", "hd ...

  9. Ubuntu 16.04 编译安装 ss

    在网上没有找到合适的适合ubuntu的ss客户端, 考虑到ss的编译安装其实就带了ss-local这样的客户端, 于是在Ubuntu下编译安装了ss. 首先去github上下载最新的安装包 https ...

  10. 移动端强大的富文本编辑器richeditor-android

    代码地址如下:http://www.demodashi.com/demo/14883.html 一.运行效果图 二.代码具体实现 1.引入richeditor-android richeditor-a ...