In Java, a Map
is a data structure that stores key-value pairs, while a List
is an ordered collection of elements. There might be situations where you need to convert a Map
into a List
. In this article, we will explore various ways to achieve this.
Method 1: Using the values()
method
The simplest way to convert a Map
into a List
is by using the values()
method, which returns a Collection
of the Map
’s values.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
List<Integer> list = new ArrayList<>(map.values());
System.out.println(list); // Output: [1, 2, 3]
}
}
Method 2: Using Java 8 Streams
Java 8 introduced Streams, which can be used to convert a Map
into a List
.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
List<Integer> list = map.values().stream().collect(Collectors.toList());
System.out.println(list); // Output: [1, 2, 3]
}
}
Method 3: Converting Map Entries to a List
Sometimes, you might want to convert a Map
into a List
of its entries. Each entry in the List
will be a Map.Entry
object.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
In conclusion, Java provides several ways to convert a Map
into a List
, each with its own use cases. Whether you’re dealing with a simple Map
or a complex one, there’s a method that can help you transform it into a List
. Happy coding! 🚀