
Introduction
This article will discuss how to convert all LinkedHashMap values to a list in java. LinkedListHashMap is used to implement a map data structure that stores key-value pairs. And the list in java provides an interface to store an ordered collection of elements. So, they are two different data structures that stores data in two entirely different manners. And in this article, we have discussed how we can convert values of all the key-value pairs stored in LinkedHashMap to a list in java.
Let’s understand this with an example:
Suppose we have a LinkedHashMap that has the following data stored as key-value pairs-
(1,5), (3,7), (6,9)
And we are going to discuss how we can convert these LinkedHashMap values to a list in java which will have - 5, 7, and 9 in sorted order.
Solution
We can convert all LinkedHashMap values to a list using java.util.LinkedHashMap.values() which don’t take any parameter and return a Collection view of the values in the HashMap.
The syntax for converting all LinkedHashMap values to a list:
LinkedListHashMap_name.values()
where “LinkedHashMap_name” is the name of the LinkedHashMap.
Java code
// Java program to Convert all LinkedHashMap values to a List
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class LinkedHashMapToList {
public static void main(String[] args)
{
// Create a LinkedHashMap
LinkedHashMap<Integer, Integer> linkedHashMapExample = new LinkedHashMap<Integer, Integer>();
// Adding key value pairs in the LinkedHashMap
linkedHashMapExample.put(1, 5);
linkedHashMapExample.put(3, 7);
linkedHashMapExample.put(6, 9);
// Method to convert all LinkedHashMap values to List
List<Integer> convertedValuesList = new ArrayList<Integer>(linkedHashMapExample.values());
// Printing the list created by converting all LinkedHashMap values to List
System.out.println("List created after conversion of all LinkedHashMap values to a list contains the following elements:");
for (Integer value : convertedValuesList) {
System.out.println(value);
}
}
}
Output:
List created after conversion of all LinkedHashMap values to a list contains the following elements:
5
7
9
Algorithm Complexity
Time Complexity: O(N), where ‘N’ is the number of elements in the LinkedHashMap
Space Complexity: O(N), where ‘N’ is the number of elements in the LinkedHashMap
Check out this problem - Find Duplicate In Array