Java 8 – Convert List to Map
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的更多相关文章
- 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> ...
- Java 集合系列14之 Map总结(HashMap, Hashtable, TreeMap, WeakHashMap等使用场景)
概要 学完了Map的全部内容,我们再回头开开Map的框架图. 本章内容包括:第1部分 Map概括第2部分 HashMap和Hashtable异同第3部分 HashMap和WeakHashMap异同 转 ...
- 【转】java 容器类使用 Collection,Map,HashMap,hashTable,TreeMap,List,Vector,ArrayList的区别
原文网址:http://www.360doc.com/content/15/0427/22/1709014_466468021.shtml java 容器类使用 Collection,Map,Hash ...
- JAVA基础--容器 Set, List, Map
Colections接口, Iterator接口, Set接口, List接口, Comparable接口, Map接口 Collections类 容器:装各种对象. 所有容器都在java.util里 ...
- Java中集合List,Map和Set的区别
Java中集合List,Map和Set的区别 1.List和Set的父接口是Collection,而Map不是 2.List中的元素是有序的,可以重复的 3.Map是Key-Value映射关系,且Ke ...
- 第51节:Java当中的集合框架Map
简书作者:达叔小生 Java当中的集合框架Map 01 Map提供了三个集合视图: 键集 值集 键-值 映射集 public String getWeek(int num){ if(num<0 ...
- java.util (Collection接口和Map接口)
1:Collection和Map接口的几个主要继承和实现类 1.1 Collection接口 Collection是最基本的集合接口,一个Collection代表一 ...
- JAVA 中的 Collection 和 Map 以及相关派生类的概念
JAVA中Collection接口和Map接口的主要实现类 Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的 ...
- JAVA中Collection接口和Map接口的主要实现类
Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements).一些Collection允许相同的元素 ...
随机推荐
- File /hbase could only be replicated to 0 nodes instead of minReplication (=1). There are 30 datanode(s) running and no node(s) are excluded in this operation.
原因: hdfs-site.xml中的配置为: <property> <name>dfs.datanode.du.reserved</name> <value ...
- pager-taglib分页处理的使用
pager-taglib是java中一个用于分页的小的框架.下面简单介绍一下它的具体使用. 一.环境的搭建: 将pager-taglib-2.0.war包拷贝到Tomcat的webapps下.启动To ...
- 去除console.log()打印语句
打印语句:console.log() ,一句话描述它! “用的时候感觉贼爽,不用的时候脑袋痛吧?” 以下提供三种解决方案: 一. webpack打包时去除,适合Vue项目 二. vscode正则匹配, ...
- vsphere storage appliance工作原理和实施
摘录自:http://www.07net01.com/storage_networking/VMwarexunihuazhiVSA_vSphere_Storage_Appliance_qunji_yi ...
- tcp线程聊天
.ServerThread package serverclient; import java.io.BufferedReader; import java.io.InputStreamReader; ...
- iOSUIWebView---快停下啦,你的愚蠢的行为
公元前 之前还是学生时代的时候给社团们学弟学妹们介绍iOS编程的时候,简单的准备了图灵ios培训第一周(使用UIWebView创建简易浏览器), NSURL *url =[NSURL URLWithS ...
- 基于py3和pymysql的数据库查询,查询某几列的数据
#python3 #xiaodeng #基于py3和pymysql的数据库查询,查询某几列的数据 import pymysql conn=pymysql.connect(....) cur=conn. ...
- Cecos国内集成系统基于rhel6.5
整体上,secos对云.虚拟化.等整体的解决方案(一键打包),很不错.做出了有益的探索.... 本次测试基于版本测试,不得说官方文档也是挺全的,很好!!!! CecOS-1.4.2-Final-170 ...
- 基于酷Q的工作秘书机器人
代码地址如下:http://www.demodashi.com/demo/14617.html 环境准备 名称 版本 Jdk 8 groovy 2.4.12 gradle 4.6 酷Q 5.12.3A ...
- Javascript中类型的判断
数据类型的判断有这么几种方式 1.一元运算符 typeOf 2.关系运算符 instanceof 3.constructor 属性 4.prototype属性 一.typeof typeof的返回值有 ...