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 a most common task related to the arrayList in java which comes in our day-to-day programming practices. For example: a list of books (ArrayList<Book>) can be convert into a HashMap which maps BookId with the object of the Book (HashMap<BookId, Book>). It can be done in many ways. We will learn a few of them in this article.

Content of the Article


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

We can convert an ArrayList to HashMap by just iterating the ArrayList. We just need to iterate on each of the element of the ArrayList and the element can converted into the 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 into a HashMap but HashMap does not maintain the order of the ArrayList. To maintain the order, we can use LinkedHashMap which is an implementation of HashMap and helps us to maintain the order of the elements. So that, we can use LinkedHashMap to convert ArrayList to HashMap. Let see how.

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));
The keyMapper takes the element of the ArrayList one by one as input and generates the key, similarly, the valueMapper takes the element of the ArrayList as input one-by-one and generates the value. Please note that, both the keyMapper and valueMapper are the instance of the Function<Input, Output> class of java.util.function package.

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 is keyMapper as s -> s which can be replaced with Function.identity() static method of java.util.function package, Function.identity() method generates output same as input i.e., without any change in input.
  • 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, 
			(oldValue, newValue) -> newValue, LinkedHashMap::new
		));
	return linkedHashMap;
}
Output
-------------ArrayList---------------
Java
C++
Python
PHP
NodeJS
--------------HashMap----------------
Java : 4
C++ : 3
Python : 6
PHP : 3
NodeJS : 6
The 3rd lambda expression is used to make choice between the old and new value, if any more than one value is generated for the same key. And, the fourth lambda is used to generates the object of LinkedHashMap.

Conclusion

In this article, we have learned how to convert ArrayList to HashMap by iterating ArrayList in java. Also, we have seen the stream APIs method of Java 8 to convert ArrayList to HashMap.
Thanks for reading this article.
If, we missed something please let us know in the comment section below.
Happy Learning

Related Posts:

Comments