How to convert a Map to List in Java? HashMap to ArrayList Example
Before converting a Map to a List in Java, we should be very clear about these data structures which are widely used in Java. So let’s begin with Map. What is Map? Map is an Interface in Java which store key and value object. It’s a Java representation of a popular hash table data structure that allows you to search an existing element in O(1) time, at the same time also makes insertion and removal easier. We use a key object to retrieve the value object by using hashing functionality provided by Map. As we have seen in how the get method of HashMap works, In Java, the equals() and hashcode() methods are an integral part of storing and retrieving objects from it. The map allows duplicate values but no duplicate keys.
Map has its implementation in various classes like HashMap , ConcurrentHashMap , and TreeMap . The Map interface also provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings.
Now let’s understand what is a List in Java, It is also an interface to provide an ordered collection based on an index. Elements can be inserted and deleted using positions and duplicate elements are allowed in the list.
There are multiple implementations of List is available in Java like ArrayList, which is based on an array, and LinkedList which is based on a linked list data structure. Now let’s see a Java program that is used to convert a Map to a List.
How to convert Map to List in Java with Example
Here is our sample program to convert a Map to a List in Java. This example is divided into three parts; In the first part, we have converted keys of HashMap into List. Map allows you to get a view of all keys of Map as Set because duplicate keys are not permitted. If you know how to convert Set to List, you can easily convert this Set of keys into a List of keys.
In 2nd example, we have converted all values of Map into List. Map provides a Collection view of all values because values can be duplicates. By using the copy constructor of Collection itself you can easily convert this Collection of Map values into a List.
In 3rd example, we will see how to convert all entries of HashMap into List. Just like keys, Map also provides a Set view of all entries. Similar to the earlier examples, we can also store all entries into List.
You can also read Core Java Volume 1 — Fundamentals by Cay S. Horstmann to learn more about different collection classes in Java.
Here is a also a nice diagram which provides a quick guide of when to use which Collection class in Java:
Java Program to convert a Map to a List
Here is our complete Java program to convert a given Map to a List in Java, for example how to convert a HashMap into an ArrayList in Java.
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Set; /** * Java Program to Convert HashMap into ArrayList in Java */ public class MapToList < public static void main(String. args) < HashMap schoolAgeCriteria = new HashMap (); // preparing HashMap with keys and values schoolAgeCriteria.put("NursuryClass age criteria", 3); schoolAgeCriteria.put("KinderGarden1 age criteria ", 4); schoolAgeCriteria.put("KinderGarden2 age criteria ", 5); schoolAgeCriteria.put("PrimarySchool age criteria", 6); System.out.println("Size of schoolAgeCriteria Map: " + schoolAgeCriteria.size()); // 1st Example : Converting HashMap keys into ArrayList Set keySet = schoolAgeCriteria.keySet(); List schoolKeyList = new ArrayList (keySet); System.out.println("Size of Key list from Map: " + schoolKeyList.size()); // print list element System.out.println("Printing HashMap keys from converted list : "); for (String key : schoolKeyList) < System.out.println(key); > // 2nd Example : Converting HashMap Values into ArrayList Collection values = schoolAgeCriteria.values(); List schoolValueList = new ArrayList (values); System.out.println("Size of Value list from Map: " + schoolValueList.size()); // print values from list System.out.println("Printing HashMap values from converted list :"); for (Integer value : schoolValueList) < System.out.println(value); > // 3rd Example : Converting HashMap into ArrayList using Entry Set Set> set = schoolAgeCriteria.entrySet(); List> schoolAgeCriteriaList = new ArrayList<>(set); Iterator> it = schoolAgeCriteriaList.iterator(); while (it.hasNext()) < Entry entry = it.next(); System.out.println("Entry from converted list : " + entry); > > > Output Size of schoolAgeCriteria Map: 4 Size of Key list from Map: 4 Printing HashMap keys from converted list : PrimarySchool age criteria KinderGarden1 age criteria KinderGarden2 age criteria NursuryClass age criteria Size of Value list from Map: 4 Printing HashMap values from converted list : 6 4 5 3 Entry from converted list : PrimarySchool age criteria=6 Entry from converted list : KinderGarden1 age criteria =4 Entry from converted list : KinderGarden2 age criteria =5 Entry from converted list : NursuryClass age criteria=3
You can see that how mappings from a Map are converted into a List which is printed in the console.
Here is also a hierarchical diagram of the Java Collection framework, you can see Map is not a subclass or sub interface of Collection, they are from the separate hierarchy.
That’s all about how to convert Map to List in Java. There are many situations when you need this like passing Map’s content into a legacy or library method which accepts List. You can use this example to convert a hash map to a list using its key value, by using the key we make ArrayList of keys also ArrayList of values. If you like to know more about the data structure provided by Java in the Collection framework, see the top 5 data structures from Java API.
- How to remove duplicate elements from ArrayList in Java? (tutorial)
- How to loop through an ArrayList in Java? (tutorial)
- Top 5 Courses to learn Spring MVC for beginners (spring courses)
- 10 Advanced Core Java Courses for Programmers (advanced courses)
- When to use ArrayList over LinkedList in Java? (answer)
- Top 5 courses to learn Java Collections and Streams (best courses)
- How to synchronize an ArrayList in Java? (read)
- How to create and initialize ArrayList in the same line? (example)
- Top 5 Courses to become full-stack Java developers (online courses)
- Difference between ArrayList and HashMap in Java? (answer)
- Top 5 Java Concurrency and thread courses (best courses)
- How to get a sublist from ArrayList in Java? (example)
- How to reverse an ArrayList in Java? (example)
- Difference between ArrayList and HashSet in Java? (answer)
- 10 Free Spring Courses for Java programmers (Free courses)
- How to sort an ArrayList in descending order in Java? (read)
- How to convert CSV String to ArrayList in Java? (tutorial)
- 10 Best Spring Boot Courses for Java developers (boot courses)
- Difference between ArrayList and Vector in Java? (answer)
Thanks for reading this article so far. If you like this Map to List conversion tutorial then, please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
How to Convert HashMap to ArrayList in Java?
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. Unlike Hashmap, an ArrayList is used to provides us with dynamic arrays in Java. It is an alternative to an array that provides a lot more flexibility in terms of storage. In this article, we will see how to convert a Hashmap to an ArrayList.
Since every element in the hashmap contains a key/value pair, it is not possible to store this key/value pair in a single ArrayList. Therefore, in order to convert a hashmap into an ArrayList, we need to maintain two separate ArrayList’s where one ArrayList is used to store the Keys and the other to store the values corresponding to those keys. The following are the various methods used to convert a hashmap to the ArrayList.
Method 1:
One way to convert is to use the constructor of the ArrayList. In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap. This set can be passed into the ArrayList while initialization in order to obtain an ArrayList containing all the keys. After obtaining the keys, we can use the values() method present in the hashmap to obtain a collection of all the values present in the hashmap. We can use this collection to initialize another array that contains all the values for the keys in the hashmap.
Преобразование карты в список в Java 8 и выше
В этом посте мы обсудим, как преобразовать карту в список в Java.
1. Преобразование Map к List
Мы знаем это Map.entrySet() возвращает набор отображений, содержащихся в этой карте. В Java 8 мы можем легко получить список пар ключ-значение с помощью преобразовать его в поток, как показано ниже:
результат:
[A=65, B=66, C=67]Вот еще более короткая версия приведенного выше кода, в которой используется ArrayList конструктор для создания списка Map.Entry объекты, содержащие как ключ, так и значение:
2. Преобразование Map к List
Мы можем получить список ключей карты, используя Map.entrySet() в Java 8 и выше:
результат:
[A, B, C]Вот лучший способ сделать это в Java 8 и выше, используя Map.keySet() :
3. Преобразование Map к List
Мы можем получить список значений карты, используя Map.entrySet() в Java 8 и выше:
результат:
[65, 66, 67]Вот лучший способ сделать это в Java 8 и выше, используя Map.values() :
Это все о преобразовании карты в список в Java.
Средний рейтинг 4.43 /5. Подсчет голосов: 7
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно