convert-map-values-to-array-list-set
Convert a Map to an Array, List or Set in Java
1. Overview
This short article will show how to convert the values of a Map to an Array, a List or a Set using plain Java as well as a quick Guava based example.
This article is part of the “Java – Back to Basic” series here on Baeldung.
Further reading:
Iterate over a Map in Java
Learn different ways of iterating through the entries of a Map in Java.
The Difference Between map() and flatMap()
Learn about the differences between map() and flatMap() by analyzing some examples of Streams and Optionals.
How to Store Duplicate Keys in a Map in Java?
A quick and practical guide to handling duplicate keys by using multimaps in Java.
2. Map Values to Array
@Test
public void givenUsingCoreJava_whenMapValuesConvertedToArray_thenCorrect() {
Map<Integer, String> sourceMap = createMap();
Collection<String> values = sourceMap.values();
String[] targetArray = values.toArray(new String[values.size()]);
}
3. Map Values to List
@Test
public void givenUsingCoreJava_whenMapValuesConvertedToList_thenCorrect() {
Map<Integer, String> sourceMap = createMap();
List<String> targetList = new ArrayList<>(sourceMap.values());
}
And using Guava:
@Test
public void givenUsingGuava_whenMapValuesConvertedToList_thenCorrect() {
Map<Integer, String> sourceMap = createMap();
List<String> targetList = Lists.newArrayList(sourceMap.values());
}
4. Map Values to Set
@Test
public void givenUsingCoreJava_whenMapValuesConvertedToS_thenCorrect() {
Map<Integer, String> sourceMap = createMap();
Set<String> targetSet = new HashSet<>(sourceMap.values());
}
5. Conclusion
As you can see, all conversions can be done with a single line, using only the Java standard collections library.
The implementation of all these examples and code snippets can be found over on GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.