
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert ArrayList to HashMap in Java
In Java the List is a child interface class which can also represents a Collection set. It is an ordered collection set, consists of the objects where duplicate values can be sorted also. Java array list is a collection framework as it presents into the java.util package and provides the dyanamic array elements in Java.
For the ArrayList we do not have to mention the size of the list. On the other hand, the HashMap<K, V> is a Java collection which can be found as a package in java.util. It contains the data values as a pair of (Key, Value).Basically, there are two different ways how we can convert an ArrayList to Hashmap by using Java
Using ArrayList Iteration
Using ArrayList Iteration with LinkedHashMap
Here is some general example of the process
Input As A List : [1="1", 2="2", 3="3"] Output As A Map : {1=1, 2=2, 3=3} Input As A List : [1="Java", 2="for", 3="JavaScript"] Output As A Map : {1=Java, 2=for, 3=JavaScript} Input : Mercedes, Audi, BMW, Harley Davidson, Triumph {Car=[Mercedes, Audi, BMW], Bike=[Harley Davidson, Triumph]}
Algorithm to Converting an ArrayList to HashMap
In this possible algorithm, we are going to show you how to perform a conversion process on an array node to make it a set of hash map. By using this algorithm, we are going to build some Java syntax to get a broad view of the problem statement.
Step 1 Start the process.
Step 2 Declare and import some Java packages.
Step 3 Create a public list.
Step 4 Declare some key as value.
Step 5 Create a constructor for the referance value.
Step 6 Assign the value of the declared keys.
Step 7 Return some private variable id.
Step 8 Declare a main public class and method.
Step 9 Declare the argument string.
Step 10 Create an array list.
Step 11 Populate the list value with data elements.
Step 12 Create and declare a map value.
Step 13 Declare the object methods.
Step 14 Create the object map value.
Step 15 Declare for and every data element to the map.
Step 16 Print the value as map and terminate the process.
Syntax to Converting an ArrayList to HashMap
ArrayList<Product> productList = new ArrayList<Product>(); productList = getProducts(); Map<String, Product> urMap = yourList.stream().collect(Collectors.toMap(Product::getField1, Function.identity())); HashMap<String, Product> productMap = new HashMap<String, Product>(); for (Product product : productList) { productMap.put(product.getProductCode(), product); } for (Product p: productList) { s.put(p.getName(), p); } for(Product p : productList){ s.put(p.getProductCode() , p); }
In this possible syntax above, we have tried to show you how to perform a conversion process on an array node to make it a set of Hash Map. With these syntax we are heading towards to build some Java codes to solve the problem statement in an efficient manner.
Approaches to Follow
Approach 1 Java program by using of convertArrayListToHashMap(), list, Collectors.toMap(), Collectors.groupingBy() and iteration method directly which converts ArrayList to Hashmap
Approach 2 Java program for list convert in HashMap with the help of Java 8 Stream and ASCII characters table methods
Approach 1
Use of ConvertArrayListToHashMap(), List, Collectors.toMap(), Collectors.groupingBy() and Iteration Method Directly Which Converts ArrayList to Hashmap.
Use of ConvertArrayListToHashMap() Method
In this possible approach, we are going to apply the convertArrayListToHashMap() method approach to perform the conversion of an array list into a set of Hash Map.
class Color{ private String name; private String code; public Color(String name, String code){ this.name = name; this.code = code; } @Override public String toString() { return name + "=" + code; } //Declare the getters and setters method }
Example
//Java program by using of convertArrayListToHashMap() method directly which converts ArrayList to Hashmap import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ARBRDD{ public static void main(String[] args){ ArrayList<String> languageList = new ArrayList<>(Arrays.asList("INDIA", "BANGLADESH", "Mitali","Bandhan", "Maitree")); System.out.println("----------#---ArrayList Is Here---#------------"); for (String language : languageList){ System.out.println(language); } System.out.println("-----------$---HashMap Is Here---$-------------"); HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList); for (Map.Entry<String, Integer> entry : languageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList){ HashMap<String, Integer> hashMap = new HashMap<>(); for (String str : arrayList) { hashMap.put(str, str.length()); } return hashMap; } }
Output
----------#---ArrayList Is Here---#------------ INDIA BANGLADESH Mitali Bandhan Maitree -----------$---HashMap Is Here---$------------- Maitree : 7 Mitali : 6 BANGLADESH : 10 INDIA : 5 Bandhan : 7
Use of ArrayList Iteration and LinkedHashMap Method
In this possible approach, we are going to apply the iteration method and hashing approach to perform the conversion of an array list into a set of Hash Map.
Example
// Java program by using convertArrayListToHashMap() method directly converts ArrayList to HashMap with ArrayList Iteration and LinkedHashMap import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.*; public class ARBRDD{ public static void main(String[] args){ ArrayList<String> languageList = new ArrayList<>(Arrays.asList( "KOLKATA", "ESPLANADE", "RAJABAZAR", "SALTLAKE", "DUMDUM")); System.out.println("----------#---ArrayList Is Here---#------------"); for (String language : languageList) { System.out.println(language); } System.out.println("-----------&---HashMap is here---&-------------"); HashMap<String, Integer> languageMap = convertArrayListToHashMap(languageList); for (Map.Entry<String, Integer> entry : languageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList){ LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>(); for (String str : arrayList) { linkedHashMap.put(str, str.length()); } return linkedHashMap; } }
Output
----------#---ArrayList Is Here---#------------ KOLKATA ESPLANADE RAJABAZAR SALTLAKE DUMDUM -----------&---HashMap is here---&------------- KOLKATA : 7 ESPLANADE : 9 RAJABAZAR : 9 SALTLAKE : 8 DUMDUM : 6
Use of a List Method
In this possible approach, we are going to apply the Java Lists method approach to perform the conversion of an array list into a set of Hash Map.
Example
// Java program by using convertArrayListToHashMap() method directly converts ArrayList to HashMap with ArrayList Iteration and LinkedHashMap by object of list import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; class Student { private Integer id; private String name; public Student(Integer id, String name){ this.id = id; this.name = name; } public Integer getId(){ return id; } public String getName(){ return name; } } public class ARBRDD { public static void main(String[] args){ List<Student> lt = new ArrayList<Student>(); lt.add(new Student(071001, "ARB")); lt.add(new Student(161097, "RDD")); lt.add(new Student(100522, "ARBRDD")); Map<Integer, String> map = new HashMap<>(); for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } System.out.println("Map Is Here: " + map); } }
Output
Map Is Here: {29185=ARB, 161097=RDD, 100522=ARBRDD}
Use of Collectors.toMap() Method
In this possible approach, we are going to apply the Collectors.toMap() method approach to perform the conversion of an array list into a set of Hash Map.
Example
//Java program for list convert in HashMap with the help of java.util.LinkedHashMap and Collectors.toMap() method import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.stream.Collectors; class Student { private Integer id; private String name; public Student(Integer id, String name){ this.id = id; this.name = name; } public Integer getId(){ return id; } public String getName(){ return name; } } public class ARBRDD { public static void main(String[] args){ List<Student> lt = new ArrayList<>(); lt.add(new Student(071001, "ARB")); lt.add(new Student(161097, "RDD")); lt.add(new Student(100522, "ARBRDD")); LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + ", " + y, LinkedHashMap::new)); map.forEach( (x, y) -> System.out.println(x + "=" + y)); } }
Output
29185=ARB 161097=RDD 100522=ARBRDD
Use of Collectors.groupingBy() Method
In this possible approach, we are going to apply the Collectors.groupingBy() method approach to perform the conversion of an array list into a set of Hash Map.
Example
//Java program for list convert in HashMap with the help of Collectors.groupingBy() method import java.util.*; import java.util.stream.Collectors; import java.util.HashMap; class Student { private Integer id; private String name; public Student(Integer id, String name){ this.id = id; this.name = name; } public Integer getId(){ return id; } public String getName(){ return name; } } public class ARBRDD { public static void main(String[] args){ List<Student> lt = new ArrayList<Student>(); lt.add(new Student(071001, "ARB")); lt.add(new Student(161097, "RDD")); lt.add(new Student(100522, "ARBRDD")); lt.add(new Student(180423, "RDDARB")); Map<Integer, List<String> > multimap = lt .stream() .collect( Collectors .groupingBy( Student::getId, Collectors .mapping( Student::getName, Collectors .toList()))); System.out.println("////MultiMap Is Here//// " + multimap); } }
Output
////MultiMap Is Here//// {29185=[ARB], 180423=[RDDARB], 100522=[ARBRDD], 161097=[RDD]}
Approach 2
Use of Java 8 Stream and ASCII Characters Table Methods.
Use of the Java 8 Stream Method
In this possible approach, we are going to apply the Java 8 Stream method approach to perform the conversion of an array list into a set of Hash Map.
colors.stream().collect(Collectors.toMap(x -> x.getName(),x -> x.getCode())); colors.stream().collect(Collectors.toMap(x -> x.getName(),x -> x.getCode(),(oldValue, newValue) -> newValue)); colors.stream().collect(Collectors.toMap(x -> x.getName(), x -> x.getCode(), (oldValue, newValue) -> newValue, TreeMap::new));
Example
//Java program for list convert in HashMap with the help of Java 8 Stream methods import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.stream.Collectors; class Color{ private String name; private String code; public Color(String name, String code){ this.name = name; this.code = code; } @Override public String toString() { return name + "=" + code; } public String getCode() { return code; } public String getName() { return name; } } public class ARBRDD{ public static void main(String[] args){ // input list of `Color` objects List<Color> colors = new ArrayList<>(); colors.add(new Color("RED COLOUR", "#FF0000")); colors.add(new Color("BLUE COLOUR", "#0000FF")); colors.add(new Color("GREEN COLOUR", "#008000")); Map<String, String> map = colors.stream() .collect(Collectors.toMap(Color::getName, Color::getCode)); System.out.println("List Value Is Here: " + colors); System.out.println("Map Value Is Here : " + map); } }
Output
List Value Is Here: [RED COLOUR=#FF0000, BLUE COLOUR=#0000FF, GREEN COLOUR=#008000] Map Value Is Here : {GREEN COLOUR=#008000, BLUE COLOUR=#0000FF, RED COLOUR=#FF0000}
Use of the With the Help of ASCII Characters Table Method
In this possible approach, we are going to apply the ASCII characters table method approach to perform the conversion of an array list into a set of Hash Map.
Example
//Java program for list convert in HashMap with the help of ASCII characters table methods import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class ARBRDD{ public static void main(String[] args){ List<String> chars = Arrays.asList("A", "R", "B", "U"); Map<String, Integer> asciiMap = new HashMap<>(); for (String s : chars){ if (asciiMap.put(s, s.hashCode()) != null){ throw new IllegalStateException("Duplicate key"); } } System.out.println(asciiMap); } }
Output
{A=65, R=82, B=66, U=85}
Conclusion
In a Java environment we can convert the Array List to a Hash Map for sure. But like array the hash map do not follow the order of the elements. To perform and construct a maintained Hash Map there is another function as LinkedHashMap, which helps a coder to maintain a Hash Map also. Today in this article, we have learned about the various methods how to convert the particular array list to Hash Map set in a Java environment.
By using the above mentioned syntax and algorithm we have built some Java codes to explain the problem statement in an efficient manner.
Read Also: Java Interview Questions and Answers