- Java 8 — Convert List to Map (Handling Duplicate Keys)
- Convert List to Map in Java
- 1. Introduction
- 3. Java 8 List To Map: Collectors.toMap()
- 4. Java 8 List into Map with Custom Objects
- 5. Java 8 List into Map with Custom Duplicate Objects Objects — MergerFunction
- 6. Convert List to LinkedHashMap and TreeMap (Sort) with Collectors.toMap() — Supplier
- 7. Conclusion
- Labels:
- SHARE:
- About Us
- Java 8 Tutorial
- Java Threads Tutorial
- Kotlin Conversions
- Kotlin Programs
- Java Conversions
- Java String API
- Spring Boot
- $show=Java%20Programs
- $show=Kotlin
- Java arraylist as map key
Java 8 — Convert List to Map (Handling Duplicate Keys)
A quick example to understand how to convert List to Map in Java 8 and exploring the different ways to do.
Convert List to Map in Java
1. Introduction
2. Collectors.toMap() Method: List into Map
Collectors is a new Java 8 utility class that provides many methods to collect the output of stream into final List or Set or Map.
public static Collector> toMap(Function keyMapper, Function valueMapper)public static Collector> toMap(Function keyMapper,Function valueMapper,BinaryOperator mergeFunction)public static > Collector toMap(Function keyMapper,Function valueMapper,BinaryOperator mergeFunction,Supplier mapSupplier)
This method is used to take the keyMapper and valueMapper Function functional interface and returns Collector object which holds our new output Map.
3. Java 8 List To Map: Collectors.toMap()
package Collectors;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.stream.Collectors;public class Java8ListToMapExamplepublic static void main(String[] args)List names = new ArrayList();names.add("james");names.add("Cisran");names.add("Paul");System.out.println("names list values are : " + names);// Names length mapMap namesLengthMap = names.stream().collect(Collectors.toMap(String::new, String::length));System.out.println("names length map : ;" + namesLengthMap);// Nanmes to upper caseMap namesUppercaseMap = names.stream().collect(Collectors.toMap(String::new, String::toUpperCase));System.out.println("names upper case map : ;" + namesUppercaseMap);>>names list values are : [james, Cisran, Paul] names length map : ; names upper case map : ;
4. Java 8 List into Map with Custom Objects
Creating an Employee class with id, name, salary, age, location along with constructor, setters & getter methods. This class will be used throughout this article.
class Employee < private int id; private String name; private long salary; private int age; private String location; public Employee(int id, String name, long salary, int age, String location) < super(); this.id = id; this.name = name; this.salary = salary; this.age = age; this.location = location; >public int getId() < return id; >public void setId(int id) < this.id = id; >public String getName() < return name; >public void setName(String name) < this.name = name; >public long getSalary() < return salary; >public void setSalary(long salary) < this.salary = salary; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >public String getLocation() < return location; >public void setLocation(String location) < this.location = location; >>package Collectors; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Java8ListToMapExample < public static void main(String[] args) < Listnames = new ArrayList(); names.add(new Employee(100, "James", 1000, 35, "USA")); names.add(new Employee(101, "Cisran", 5000, 25, "UK")); names.add(new Employee(102, "Paul", 7000, 40, "AUS")); System.out.println("Employees list values are : " + names); // Map - Id, Name Map idNameMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getName)); System.out.println("Map " + idNameMap); // Map - Id, Salary Map idSalaryMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getSalary)); System.out.println("Map " + idSalaryMap); // Map - Id, Age Map idAgeMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getAge)); System.out.println("Map " + idAgeMap); // Map - Id, Location Map idLocationMap = names.stream() .collect(Collectors.toMap(Employee::getId, Employee::getLocation)); System.out.println("Map " + idLocationMap); > >Employees list values are : [Collectors.Employee@60f82f98, Collectors.Employee@35f983a6, Collectors.Employee@7f690630] Map Map Map Map
5. Java 8 List into Map with Custom Duplicate Objects Objects — MergerFunction
Next, Run the full code as below. toMap() method, we are passing getId() as the key that means id should be unique in the list but it has duplicates for id 102. We should see the runtime exception now.
package Collectors; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Java8ListToMapExample < public static void main(String[] args) < Listnames = new ArrayList(); names.add(new Employee(100, "James", 1000, 35, "USA")); names.add(new Employee(101, "Cisran", 5000, 25, "UK")); names.add(new Employee(102, "Paul", 7000, 40, "AUS")); names.add(new Employee(102, "Gena", 3000, 30, "NZ")); // Map - Id, Name Map idNameMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getName)); System.out.println("Map " + idNameMap); > >Exception in thread "main" java.lang.IllegalStateException: Duplicate key Paul at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133) at java.util.HashMap.merge(HashMap.java:1254) at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320) at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169) at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at Collectors.Java8ListToMapExample.main(Java8ListToMapExample.java:21)In this case, if you know which one to ignore then we are good to use the toMap() overloaded method with mergeFunction.
public static Collector> toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)BinaryOperator functional interface takes the same type as input and returns the same type as output. This is a subinterface to BiFunction and takes two parameters.
public class Java8ListToMapExample < public static void main(String[] args) < Listnames = new ArrayList(); names.add(new Employee(100, "James", 1000, 35, "USA")); names.add(new Employee(101, "Cisran", 5000, 25, "UK")); names.add(new Employee(102, "Paul", 7000, 40, "AUS")); names.add(new Employee(102, "Gena", 3000, 30, "NZ")); // Map - Id, Name Map idNameMap = names.stream() .collect(Collectors.toMap(Employee::getId, Employee::getName, (oldValue, newValue) -> newValue)); System.out.println("Map " + idNameMap); > >Map idNameMap = names.stream() .collect(Collectors.toMap(Employee::getId, Employee::getName, (oldValue, newValue) -> oldValue));6. Convert List to LinkedHashMap and TreeMap (Sort) with Collectors.toMap() — Supplier
As of now, we’ve seen how to convert List to Map and default output of key-value pair is stored into HashMap.
toMap() has another overloaded method that takes 4th argument Supplier. From the Supplier, You need to pass the LinkedHashMap or TreeMap object as shown in the below example.
package Collectors; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.TreeMap; import java.util.stream.Collectors; public class Java8ListToMapExample < public static void main(String[] args) < Listnames = new ArrayList(); names.add(new Employee(100, "James", 1000, 35, "USA")); names.add(new Employee(101, "Cisran", 5000, 25, "UK")); names.add(new Employee(102, "Paul", 7000, 40, "AUS")); names.add(new Employee(102, "Gena", 3000, 30, "NZ")); // Map - Id, Name LinkedHashMap linkedhashMap = names.stream().collect(Collectors.toMap(Employee::getId, Employee::getName, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); System.out.println("LinkedHashMap " + linkedhashMap); // Map - Id, Name TreeMap treeMap = names.stream().collect(Collectors.toMap(Employee::getName, Employee::getLocation, (oldValue, newValue) -> oldValue, TreeMap::new)); System.out.println("TreeMap " + treeMap); > >From the output, First LinkedHashMap stored 3 key-value pairs whereas TreeMap has 4 key-value pairs because the key is an emp name which is not having the duplicates names.
7. Conclusion
In this article, You’ve seen in-depth about how to convert List to Map in Java 8. How to deal with Custom objects in List and convert them into Map.
By default, toMap() method converts List into HashMap but there are some cases you may encounter to convert to LinkedHashMap or TreeMap. To convert to your own map, you need to provide the Supplier to toMap() function.
Labels:
SHARE:
About Us
Java 8 Tutorial
- Java 8 New Features
- Java 8 Examples Programs Before and After Lambda
- Java 8 Lambda Expressions (Complete Guide)
- Java 8 Lambda Expressions Rules and Examples
- Java 8 Accessing Variables from Lambda Expressions
- Java 8 Method References
- Java 8 Functional Interfaces
- Java 8 — Base64
- Java 8 Default and Static Methods In Interfaces
- Java 8 Optional
- Java 8 New Date Time API
- Java 8 — Nashorn JavaScript
Java Threads Tutorial
Kotlin Conversions
Kotlin Programs
Java Conversions
- Java 8 List To Map
- Java 8 String To Date
- Java 8 Array To List
- Java 8 List To Array
- Java 8 Any Primitive To String
- Java 8 Iterable To Stream
- Java 8 Stream To IntStream
- String To Lowercase
- InputStream To File
- Primitive Array To List
- Int To String Conversion
- String To ArrayList
Java String API
- charAt()
- chars() — Java 9
- codePointAt()
- codePointCount()
- codePoints() — Java 9
- compareTo()
- compareToIgnoreCase
- concat()
- contains()
- contentEquals()
- copyValueOf()
- describeConstable() — Java 12
- endsWith()
- equals()
- equalsIgnoreCase()
- format()
- getBytes()
- getChars()
- hashcode()
- indent() — Java 12
- indexOf()
- intern()
- isBlank() — java 11
- isEmpty()
- join()
- lastIndexOf()
- length()
- lines()
- matches()
- offsetByCodePoints()
- regionMatches()
- repeat()
- replaceFirst()
- replace()
- replaceAll()
- resolveConstantDesc()
- split()
- strip(), stripLeading(), stripTrailing()
- substring()
- toCharArray()
- toLowerCase()
- transform() — Java 12
- valueOf()
Spring Boot
$show=Java%20Programs
$show=Kotlin
accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
A quick example to understand how to convert List to Map in Java 8 and exploring the different ways to do.
Java arraylist as map key
“Анна Ивановна Решетникова, 4211 717171” И как они собирались хранить такой номер паспорта в типе Integer? Тем самым показав, что номер паспорта хранить в базе данных как число — это не лучшая идея. Так как номера паспорта могут содержать дефисы, пробелы, буквы и т.д. Поправьте меня, если я не прав. Иначе у меня вопросы к господину Милану.
Скажите, почему хронология вывода на экран поменялась?
Получение списка всех ключей и значений Еще одна удобная особенность HashMap — можно по-отдельности получить список всех ключей и всех значений. Для этого используются методы keySet() и values() Для чего в примере создаются Set и ArrayList? Если в sout можно прямо вызвать методы keySet() и values()?
Возможно ли в HashMap переопределить метод toString() и если да, то каким образом? P/S: Спросил нынче модный ChatGPT, так он какую-то чушь городит: то пишет можно и даёт нерабочие коды, каждый раз разные, то пишет что нельзя потому что HashMap происходит от абстрактного класса. Хотя я уже понял что верить ему нельзя во всем, на вопрос можно ли реализовать в Java множественное наследование (не через интерфейсы) он бодро рапортовал, что конечно можно и вывалил код типа public сlass A extends B, C, который естественно не работает. Извините за возможный оффтоп. Так что роботы пока не завоюют мир, поэтому, вопрос по toString() все еще актуален. )