Java – Convert a Map to Array, List or Set

This Java tutorial will teach how to convert Map keys and values to the array, List or Set. Java maps are a collection of key-value pairs. The Map keys are always unique but can have duplicate values.

1. Convert Map to Array

For demo purposes, let us create a Map with String keys and Integer values.

Map<String, Integer> map = Map.of("A",1, "B", 2, "C", 3);

The Map.values() returns a collection view of the values contained in this map. Use Collection.toArray() to get the array from collection elements. This method takes the runtime type of the returned array.

Collection<Integer> values =  map.values();
Integer valArray[] = values.toArray(new Integer[0]);

Similarly, we can collect the Map keys into an array. Map.keyset() returns the Set of all the keys in a Map. Using Set.toArray() we can convert it to an array of Strings.

String keyArray[] = map.keySet().toArray(new String[0]);

2. Convert Map to List

We can collect the Map values into a List using the ArrayList constructor which takes a collection of values as its parameter.

List<Integer> valList = new ArrayList<>(map.values());

We can use Java Streams to achieve the same result.

List<Integer> listOfValues = map.values().stream().collect(Collectors.toCollection(ArrayList::new));

Likewise, we can convert Map keys to List using plain Java and Streams.

List<String> keyList = new ArrayList<>(map.keySet()); //ArrayList Constructor

List<String> listOfKeys = map.keySet().stream().collect(Collectors.toCollection(ArrayList::new)); //Streams

3. Convert Map to Set

We can use the HashSet constructor or Streams to convert Map values to a Set.

Set<Integer> valSet = new HashSet<>(map.values()); //HashSet Constructor
Set<Integer> setOfValues = map.values().stream().collect(Collectors.toCollection(HashSet::new)); //using Streams

The Map.keySet() returns a Set view of all the keys in the Map.

Set<String> keySet = map.keySet();

4. Conclusion

This tutorial taught us how to convert Java Map keys and values into an Array, List or Set with simple examples. We learned to use the ArrayList and HashSet constructors as well as Stream APIs.

Happy Learning!!


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode