Is a HashMap a list Java?
HashMap and ArrayList are two most used data structures in java. Both classes inherit from different hierarchies. HashMap is inherited from Map interface which represents the data in the form of key-value pairs. ArrayList is inherited from List interface which arranges the data in the sequential manner. Conversion of HashMap to ArrayList has also become a regular question in the java interviews as there is no direct methods in HashMap which converts theHashMap to ArrayList. In this post, we will see how to convert HashMap to ArrayList in java with examples. At the end, we will also see java 8 code to convert map to list in java. Show How To Convert HashMap To ArrayList In Java?As HashMap contains key-value pairs, there are three ways you can convert given HashMap to ArrayList. You can convert HashMap keys into ArrayList or you can convert HashMap values into ArrayList or you can convert key-value pairs into ArrayList.Lets see these three methods in detail. a) Conversion Of HashMap Keys Into ArrayList : For this, we use keySet() method of HashMap which returns the Set containing all keys of the HashMap. And then we pass this Set while constructing the ArrayList. //Creating a HashMap object HashMapb) Conversion Of HashMap Values Into ArrayList : For this, we use values() method of HashMap which returns the Collection containing all values of theHashMap. Then we usethisCollection tocreate theArrayList of values. //Creating a HashMap object HashMapc) Conversion Of HashMaps Key-Value Pairs Into ArrayList : For this, we use entrySet() method of HashMap which returns the Set of Entry Java Program To Convert HashMap To ArrayList :Below example converts the studentPerformanceMap to listOfKeys, listOfValues and listOfEntry. import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; public class Java8MapToListExamples { public static void main(String[] args) { //Creating a HashMap object HashMapOutput : ArrayList Of Keys : Java 8 Convert Map To Lista) Java 8 Convert Map Keys To List //Creating a Map object Mapb) Java 8 Convert Map Values To List //Creating a Map object Mapc) Java 8 Sort And Convert Map Keys To List //Creating a Map object Mapd) Java 8 Sort And Convert Map Values To List Note : You can also provide Comparator to sorted() method to sort the keys or values as you wish. Also Read : How HashMap works internally in java? What is load factor and initial capacity of HashMap? 15 Java HashMap Programs And Examples References :
|