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. 使用docker api

    前提: 系统centos 7 docker version 1.10.3 使用systemd启动docker 访问方式: 修改/usr/lib/systemd/system/docker.servic ...

  2. javascript string replace 正则替换

    利用正则式实现首字母大写,丧心病狂是不是?好好的substr不用. JavaScript replace() 方法 r = /^(.)(?=.*)/; str = 'abc'; var str2 = ...

  3. linux CPU占用率高(转)

    来自:http://www.cnitblog.com/houcy/archive/2012/11/28/86801.html 1.用top命令查看哪个进程占用CPU高 gateway网关进程14094 ...

  4. python 大小端数据转换

    "6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000".decode('hex')[::-1].enc ...

  5. MUI(拍照+系统相册)图片上传剪切预览

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  6. ADAMS与外部程序通信(Adams Command Server)

    The Adams Command Server is an Adams View (or Adams Car) component that manages communication betwee ...

  7. HttpServletRequest对象(一)

    javaweb学习总结(十)——HttpServletRequest对象(一) 一.HttpServletRequest介绍 HttpServletRequest对象代表客户端的请求,当客户端通过HT ...

  8. ios 中sqlite的用法

    #import <sqlite3.h> @interface ViewController () { sqlite3 *_sqldb; } @end @implementation Vie ...

  9. (原)python中不同文件之间使用所谓的全局变量

    转载请注明出处: http://www.cnblogs.com/darkknightzh/p/8108640.html 参考网址: https://www.cnblogs.com/20150705-y ...

  10. <转>字节码指令

    本文转自:http://www.cnblogs.com/nazhizq/p/6525263.html 在llimits.h文件中定义了指令的类型.其实就是32个字节. typedef lu_int32 ...