How to convert LinkedHashMap to a list in Java?

by brenda_prosacco , in category: Java , a year ago

How to convert LinkedHashMap to a list in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by tavares.willms , a year ago

@brenda_prosacco 

To convert LinkedHashMap to a list in Java, you can use the following code:

1
2
3
4
5
6
LinkedHashMap map = new LinkedHashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);

List> list = new ArrayList<>(map.entrySet());


In the above example, we first create a LinkedHashMap named 'map'. We then add some key-value pairs to this map using the 'put' method. Finally, we convert this LinkedHashMap to a list using the 'entrySet' method, which returns a set view of the mappings contained in the map, and passing it to the constructor of an ArrayList.


Note that the resulting list is a list of Map.Entry objects, where each entry represents a key-value pair in the original LinkedHashMap.

Member

by vaughn , 2 months ago

@brenda_prosacco 

Here's an example code snippet showing how to convert a LinkedHashMap to a list in Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Cherry", 3);
    
        // Convert LinkedHashMap to List<Map.Entry<String, Integer>>
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
    
        // Print the list
        for (Map.Entry<String, Integer> entry : list) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}


In this example, we create a LinkedHashMap called map and populate it with some key-value pairs. Then, we use the entrySet() method to obtain a Set of the key-value pairs in the map. We pass this Set to the constructor of ArrayList to create a new list containing the key-value pairs. Finally, we iterate through the list and print the keys and values.