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
The Difference Between map() and flatMap()
How to Store Duplicate Keys in a Map in Java?
2. Map Values to Array
First, letβs look at converting the values of the Map into an array, using plain java:
@Test
public void givenUsingCoreJava_whenMapValuesConvertedToArray_thenCorrect() {
Map<Integer, String> sourceMap = createMap();
Collection<String> values = sourceMap.values();
String[] targetArray = values.toArray(new String[0]);
}
Note, that toArray(new T[0]) is the preferred way to use the method over the toArray(new T[size]). As Aleksey ShipilΓ«v proves in his blog post, it seems faster, safer, and cleaner.
3. Map Values to List
Next, letβs convert the values of a Map to a List β using plain Java:
@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
Finally, letβs convert the values of the Map to a Set, using plain java:
@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.
