Several Java 8 examples show how to put a collection of objects (List) into a Map and how to handle multiple duplicate keys.Hosting.java
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 toMap — Collectors. ToMap ()
Create a Hosting
object collection, and use Collectors. ToMap
to convert it to a Map.
TestListMap.java
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!
2.1 Run below code, and duplicated key errors will be thrown!
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);
}
}
Output: This error is somewhat misleading. It should show the value of “linode” instead of 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 In order to solve the problem of repeating key above, the third parameter is added to solve:
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}
Note
(oldValue, newValue) -> OldValue </ code> = = & gt; If the key is repeated, do you choose oldKey or newKey?
3.3 the 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
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=80000, mkyong.com=1}
In the above example, the stream has been sorted before collect so that “linode.com= 100,000” becomes “oldValue”.
References
- Java 8 Collectors JavaDocJava 8 — How to sort a MapJava 8 Lambda: Comparator example
Read More:
- [Solved] stream Convert list to map Error: java.lang.IllegalStateException: Duplicate key
- Java will convert Excel to list set or JSON, export excel file to local, excel import and export, easyexcel tool class
- How to convert a Java string into a number (stringtonumber)
- JAVA: How to Convert PDF from Color to Grayscale
- [Solved] Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
- [Solved] Failed to convert value of type ‘java.lang.String‘ to required type ‘java.util.Date‘;
- [Solved] Read the resources resource and convert it to file error: java.io.filenotfoundexception
- [Solved] Java.lang.ClassCastException: [Ljava.lang.Long; cannot be cast to java.util.List
- List: How to de-duplication according to an attribute of an object
- [Solved] Failed to instantiate java.util.List using constructor NO_CONSTRUCTOR with arguments
- How to Solve java server error (java application Run Normally)
- JAVA: How to Use Minio to upload pictures
- How to Converte Java objects to jsonnode in Jackson (Four Methods)
- JAVA: How to Use Multipartfile to upload Files
- JAVA: How to Read JSON Format Data (Web Game Development)
- Java: How to Find the Minimum Value from a Random Array by Bubble Sort Method
- [Solved] SpringBoot Date Convert Error: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime`
- How to Close the Current Form in JAVA Swing
- AlmaLinux 9.1: How to Install java11
- How to Solve ERROR: Java 1.7 or later is required to run Apache Drill