ArrayList is a resizable array. It is under the java package java.util. It gives dynamic arrays in Java. ArrayList is useful in programs where a lot of changes in the array are required but these are also slower than the standard arrays. The elements in an ArrayList can be added and removed whenever needed.
HashMap is a data structure that stores items in “Key/Value” pairs. They can be accessed by an index of another type like a String. The HashMap is denoted as HashMap<Key, Value>. This is very similar to HashTable, but it permits the use of null values and null keys. It does not return the Keys and Values in the same order in which they are stored into the HashMap. It is also under the java package java.util.
- Initial ArrayList is having no duplicates
- Initial ArrayList is having duplicate values.
Case 1: The most ideal way to convert an ArrayList into HashMap before Java 8 is through iterating over the given ArrayList using enhanced for-loop and inserting the String as the key and its length as the value into HashMap. Here, each element of the ArrayList can be converted into a key-value pair and store in the HashMap. This method also handles any duplicate in the ArrayList as well because of inserted entries that override values in case of duplicate keys. In this case, no error or exception is thrown.
Example: Initial ArrayList is having no duplicates
ArrayList: Car Bike Bus Cycle Rickshaw HashMap: Bus : 3 Rickshaw : 8 Car : 3 Bike : 4 Cycle : 5
Case 2: Initial ArrayList is having duplicate values where it overrides the value due to a duplicate key in HashMap.
ArrayList: Car Bike Bus Cycle Rickshaw Car Bike HashMap: Bus : 3 Rickshaw : 8 Car : 3 Bike : 4 Cycle : 5
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.