Open In App

How to Convert all LinkedHashMap Key-Value pairs to List in Java?

Improve
Improve
Like Article
Like
Save
Share
Report

The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. 

We have to convert all LinkedHashMap key-values pairs to list, so we have a LinkedHashMap object that contains some pairs of key-values and we have to convert it into list using keySet() and values() method.

keySet(): This method is used to get the keys of its called LinkedHashMap object.

values(): This method is used to get the values of its called LinkedHashMap object.

Approach:

  • Create a LinkedHashMap that contain some keys and values pair.
  • Create a List1 that contain the keys of LinkedHashMap object.
  • Create a List2 that contain the values of LinkedHashMap object.

Code:

Java




// Java program to Convert all LinkedHashMap
// Key-Value pairs to List
  
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
  
public class Sias {
  
    public static void main(String[] args)
    {
  
        // create LinkedHashMap
        LinkedHashMap<Integer, String> lhmap
            = new LinkedHashMap<Integer, String>();
  
        // add elements in LinkedHashMap
        lhmap.put(1, "One");
        lhmap.put(2, "Two");
        lhmap.put(3, "Three");
        lhmap.put(4, "Four");
        lhmap.put(5, "Five");
  
        // Create List 1 that store keys
        List<Integer> list1
            = new ArrayList<Integer>(lhmap.keySet());
  
        // display List 1
        System.out.println("List 1 - " + list1);
  
        // Create List 2 that store values
        List<String> list2
            = new ArrayList<String>(lhmap.values());
  
        // display List 1
        System.out.println("List 2 - " + list2);
    }
}


Output

List 1 - [1, 2, 3, 4, 5]
List 2 - [One, Two, Three, Four, Five]


Last Updated : 28 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads