A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and List can contain duplicate values.
The map has two values (a key and value), while a List only has one value (an element). So we can generate two list – a list of values and list of keys from a Map.
Assuming map is the instance of Map
- map.values() will return a Collection of the map’s values.
- map.keySet() will return a Set of the map’s keys.
we can generate List from Map in several ways-
We can convert Map keys to List of Keys by passing set of map keys generated by map.keySet() method to ArrayList Constructor Parameter.
List ListofKeys = new ArrayList(map.keySet());
We can convert Map keys to List of Values by passing collection of map values generated by map.values() method to ArrayList Constructor Parameter.
List Listofvalues= new ArrayList(map.values());
You can also use Stream API to convert map keys and values to respective lists.
List ListofKeys = map.keyset().stream(). collect(Collectors.toCollection(ArrayList::new)); List Listofvalues= map.values().stream(). collect(Collectors.toCollection(ArrayList::new));
The stream() method returns a stream of the keys from the Set of the map keys returned by Map.keySet(). The collect() method of the Stream class is collects the stream of keys in a List.The Collectors.toCollection(ArrayList::new) passed to the collect() method to collect as new Arraylist. You can collect elements of Stream in a ArrayList, LinkedList, or any other List implementation.
Example: Given RollNo and Student Name of N students as input. First, we create a Map where Rollno is key because Rollno is unique and Name as Value for Map then convert this map to list of values and keys respectively. Where the generated list of keys contains RollNo of students and list of Values contains Name of Students.
Input : Enter No of Students 5 101 aman 102 amar 103 suraj 104 pritam Output : List of RollNo of Students [101, 102, 103, 104] List of Name of Students [aman, amar, suraj, pritam]
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.