How to Convert all LinkedHashMap Values to a List in Java

Introduction

The linked list is one of the most important data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

Problem Statement

In this problem, we have to convert all the LinkedHashMap values to a List in Java.

Problem Statement Understanding

Let us suppose that we have a LinkedHashMap that has key-value pairs:
(1,23), (2,45), (3,67).

Now, we have to create a Linked List, which contains all the values of the given LinkedHashMap. So, the resultant list will be:

If the LinkedHashMap has key-value pairs as:
(1,10), (2,20), (3,30), (4,40).

Now the resultant linked list which will contain all the values of give LinkedHashMap will be:

Explanation: The output list contains all the values present in the LinkedHashMap.

A LinkedHashMap stores key-value pairs, and a List is an ordered collection of elements. Let us have a glance at the approach.

Approach and Algorithm

To convert all the values of a LinkedHashMap to a List in Java, we can use the values() method. The values() is a method of the LinkedHashMap that returns a Collection of all the values in the map object. We can then convert this collection to a List object.

Syntax - LinkedHashMap.values()

Code Implementation


import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;


public class LinkedHashMapToListExample {
  
    public static void main(String[] args)
    {

        LinkedHashMap lhmap
            = new LinkedHashMap();

        lhmap.put(1, 23);
        lhmap.put(2, 45);
        lhmap.put(3, 67);

        List listValues
            = new ArrayList(lhmap.values());

        System.out.println("List contains:");
        for (Integer value : listValues) {
            System.out.println(value);
        }
    }
}

Output

List contains:
23
45
67

Time Complexity: O(n), where n is the size of the LinkedHashMap.
Space Complexity: O(n), where n is the size of the LinkedHashMap.

So, in this article, we have tried to explain the most efficient approach to convert all the LinkedHashMap values to a List in Java. Java Collections is an important concept when it comes to coding interviews. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes visit Linked List.

Previous post Rearrange a given Linked List in-place
Next post LinkedList addAll() method in Java

Leave a Reply

Your email address will not be published. Required fields are marked *