Skip to main content

ArrayList to HashMap in Java

How to convert ArrayList to HashMap in Java?

In this article, we are going to learn how we can convert ArrayList to HashMap in java. This is the most common task related to an ArrayList in Java which comes in our day-to-day programming practices. For example: an ArrayList<Book> (list of books) can be convert into HashMap<BookId, Book> (a HashMap which map BookId with actual Book Object). To achieve this, we have many alternatives. Let's learn a few of them.

Content of the Article

How to convert ArrayList to HashMap in Java - Using ArrayList Iteration?

We can convert an ArrayList to HashMap by iterating ArrayList in java. We just need to iterate each element of ArrayList and by using the element create a key-value pair and store into the HashMap.

Example 1: ArrayList to HashMap in Java - Using ArrayList Iteration

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languageList = new ArrayList<>(
                                Arrays.asList("Java", "C++", "Python", "PHP" , "NodeJS"));
                System.out.println("-------------ArrayList---------------");
                for (String language : languageList) {
                        System.out.println(language);
                }
                System.out.println("--------------HashMap----------------");
                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---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
C++ : 3
PHP : 3
NodeJS : 6
Python : 6

How about the order of the ArrayList?

As we can see, the ArrayList is converted to a HashMap but HashMap does not maintain the order of the ArrayList. We can use LinkedHashMap which is an implementation of HashMap and maintain the order so that we can use LinkedHashMap to convert ArrayList to HashMap.

Example 2: ArrayList to HashMap in Java - Using ArrayList Iteration with LinkedHashMap

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---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
C++ : 3
Python : 6
PHP : 3
NodeJS : 6

How to convert ArrayList to HashMap in Java - Using Java 8 Stream APIs?

Java 8 introduced stream APIs and lambda expression which provides a very easy way to convert an ArrayList to HashMap.
  • Through stream API methods, we can start the stream of the ArrayList and with the help of collect() method and the java.util.stream.Collectors.toMap() static method, we can collect each element of ArrayList to HashMap.
  • And By using lambda expression, we can write keyMapper and valueMapper.
Syntax
Map<K, V> map = arrayList.stream().collect(Collectors.toMap(keyMapper, valueMapper));

Example 3: ArrayList to HashMap in Java - Using Java 8 Stream APIs

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class ArrayListExample {
        public static void main(String[] args) {
                ArrayList<String> languageList = new ArrayList<>(
                                Arrays.asList("Java", "C++", "Python", "PHP", "NodeJS"));
                System.out.println("-------------ArrayList---------------");
                for (String language : languageList) {
                        System.out.println(language);
                }
                System.out.println("--------------HashMap----------------");
                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<>(
                        arrayList.stream().collect(Collectors.toMap(s -> s, s -> s.length()))
                );
                return hashMap;
        }
}
Output
-------------ArrayList---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
PHP : 3
C++ : 3
NodeJS : 6
Python : 6
We have used two lambda expression here,
  • One for keyMapper as s -> s which can be replaced with Function.identity() static method of java.util.function package
  • And another for valueMapper as s -> s.length() can be replaced with method refernce String::length.
So we can rewrite the method as:
private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList) {
        HashMap<String, Integer> hashMap = new HashMap<>(
                arrayList.stream().collect(Collectors.toMap(Function.identity(), String::length))
        );
        return hashMap;
}

Using Java 8 Stream APIs with LinkedHashMap to maintain order

Example 4: ArrayList to HashMap in Java - Using Java 8 Stream APIs with LinkedHashMap to maintain order

private static HashMap<String, Integer> convertArrayListToHashMap(ArrayList<String> arrayList) {
        LinkedHashMap<String, Integer> linkedHashMap = arrayList.stream().collect(
                Collectors.toMap(
                        Function.identity(), String::length, (v1, v2) -> v2, LinkedHashMap::new
                ));
        return linkedHashMap;
}
Output
-------------ArrayList---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
C++ : 3
Python : 6
PHP : 3
NodeJS : 6

Related Posts:


Conclusion

In this article, we have learned how to convert ArrayList to HashMap using ArrayList Iteration in Java. Also, we have seen the stream APIs method of Java 8 to convert ArrayList to HashMap.

Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…