- Java – Convert a Map to Array, List or Set
- Java 8: How to Convert a Map to List
- Convert Map to List of Map.Entry
- Convert Map to List using Two Lists
- Convert Map to List with Collectors.toList() and Stream.map()
- Free eBook: Git Essentials
- Convert Map to List with Stream.filter() and Stream.sorted()
- Convert Map to List with Stream.flatMap()
- Conclusion
- Java 8 – Convert Map to List
- Java 8 – Map To List
- 3. Java 8 – Convert Map into 2 List
- References
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.
For demo purposes, let us create a Map with String keys and Integer values.
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 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]);
We can collect the Map values into a List using the ArrayList constructor which takes a collection of values as its parameter.
List valList = new ArrayList<>(map.values());
We can use Java Streams to achieve the same result.
List listOfValues = map.values().stream().collect(Collectors.toCollection(ArrayList::new));
Likewise, we can convert Map keys to List using plain Java and Streams.
List keyList = new ArrayList<>(map.keySet()); //ArrayList Constructor List listOfKeys = map.keySet().stream().collect(Collectors.toCollection(ArrayList::new)); //Streams
We can use the HashSet constructor or Streams to convert Map values to a Set.
Set valSet = new HashSet<>(map.values()); //HashSet Constructor Set 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.
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.
Java 8: How to Convert a Map to List
A Java Map implementation is an collection that maps keys to values. Every Map Entry contains key/value pairs, and every key is associated with exactly one value. The keys are unique, so no duplicates are possible.
A common implementation of the Map interface is a HashMap :
Map students = new HashMap<>(); students.put(132, "James"); students.put(256, "Amy"); students.put(115, "Young"); System.out.println("Print Map: " + students);
We’ve created a simple map of students (Strings) and their respective IDs:
A Java List implementation is a collection that sequentially stores references to elements. Each element has an index and is uniquely identified by it:
List list = new ArrayList<>(Arrays.asList("James", "Amy", "Young")); System.out.println(list); System.out.println(String.format("Third element: %s", list.get(2));
[James, Amy, Young] Third element: Young
The key difference is: Maps have two dimensions, while Lists have one dimension.
Though, this doesn’t stop us from converting Maps to Lists through several approaches. In this tutorial, we’ll take a look at how to convert a Java Map to a Java List:
Convert Map to List of Map.Entry
Java 8 introduced us to the Stream API — which were meant as a step towards integrating Functional Programming into Java to make laborious, bulky tasks more readable and simple. Streams work wonderfully with collections, and can aid us in converting a Map to a List.
The easiest way to preserve the key-value mappings of a Map , while still converting it into a List would be to stream() the entries, which consist of the key-value pairs.
The entrySet() method returns a Set of Map.Entry elements, which can easily be converted into a List , given that they both implement Collection :
List> singleList = students.entrySet() .stream() .collect(Collectors.toList()); System.out.println("Single list: " + singleList);
Single list: [256=Amy, 115=Young, 132=James]
Since Streams are not collections themselves — they just stream data from a Collection — Collectors are used to collect the result of a Stream ‘s operations back into a Collection . One of the Collectors we can use is Collectors.toList() , which collects elements into a List .
Convert Map to List using Two Lists
Since Maps are two-dimensional collections, while Lists are one-dimensional collections — the other approach would be to convert a Map to two List s, one of which will contain the Map’s keys, while the other would contain the Map’s values.
Thankfully, we can easily access the keys and values of a map through the keySet() and values() methods.
The keySet() method returns a Set of all the keys, which is to be expected, since keys have to be unique. Due to the flexibility of Java Collections — we can create a List from a Set simply by passing a Set into a List ‘s constructor.
The values() method returns a Collection of the values in the map, and naturally, since a List implements Collection , the conversion is as easy as passing it in the List ‘s constructor:
List keyList = new ArrayList(students.keySet()); List valueList = new ArrayList(students.values()); System.out.println("Key List: " + keyList); System.out.println("Value List: " + valueList);
Key List: [256, 115, 132] Value List: [Amy, Young, James]
Convert Map to List with Collectors.toList() and Stream.map()
We’ll steam() the keys and values of a Map , and then collect() them into a List :
List keyList = students.keySet().stream().collect(Collectors.toList()); System.out.println("Key list: " + keyList); List valueList = students.values().stream().collect(Collectors.toList()); System.out.println("Value list: " + valueList);
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Key list: [256, 115, 132] Value list: [Amy, Young, James]
This approach has the advantage of allowing us to perform various other operations or transformations on the data before collecting it. For example, knowing that we’re working with Strings — we could attach an anonymous function (Lambda Expression). For example, we could reverse the bytes of each Integer (key) and lowercase every String (value) before collecting them into a List :
List keyList = students.keySet() .stream() .map(Integer::reverseBytes) .collect(Collectors.toList()); System.out.println("Key list: " + keyList); List valueList = students.values() .stream() .map(String::toLowerCase) .collect(Collectors.toList()); System.out.println("Value list: " + valueList);
Note: The map() method returns a new Stream in which the provided Lambda Expression is applied to each element. If you’d like to read more about the Stream.map() method, read our Java 8 — Stream.map() tutorial.
Running this code transforms each value in the streams before returning them as lists:
Key list: [65536, 1929379840, -2080374784] Value list: [amy, young, james]
We can also use Collectors.toCollection() method, which allows us to chose the particular List implementation:
List keyList = students.keySet() .stream() .collect(Collectors.toCollection(ArrayList::new)); List valueList = students.values() .stream() .collect(Collectors.toCollection(ArrayList::new)); System.out.println("Key list: " + keyList); System.out.println("Value list: " + valueList);
Key list: [256, 115, 132] Value list: [Amy, Young, James]
Convert Map to List with Stream.filter() and Stream.sorted()
We’re not only limited to mapping values to their transformations with Stream s. We can also filter and sort collections, so that the lists we’re creating have certain picked elements. This is easily achieved through sorted() and filter() :
List sortedValueList = students.values() .stream() .sorted() .collect(Collectors.toList()); System.out.println("Sorted Values: " + sortedValueList);
After we sorted the values we get the following result:
Sorted Values: [Amy, James, Young]
We can also pass in a custom comparator to the sorted() method:
List sortedValueList = students.values() .stream() .filter(value-> value.startsWith("J")) .collect(Collectors.toList()); System.out.println("Sorted Values: " + sortedValueList);
If you’d like to read more about the sorted() method and how to use it — we’ve got a guide on How to Sort a List with Stream.sorted().
Convert Map to List with Stream.flatMap()
The flatMap() is yet another Stream method, used to flatten a two-dimensional stream of a collection into a one-dimensional stream of a collection. While Stream.map() provides us with an A->B mapping, the Stream.flatMap() method provides us with a A -> Stream mapping, which is then flattened into a single Stream again.
If we have a two-dimensional Stream or a Stream of Streams, we can flatten it into a single one. This is conceptually very similar to what we’re trying to do — convert a 2D Collection into a 1D Collection. Let’s mix things up a bit by creating a Map where the keys are of type Integer while the values are of type List :
Map> newMap = new HashMap<>(); List firstName = new ArrayList(); firstName.add(0, "Jon"); firstName.add(1, "Johnson"); List secondName = new ArrayList(); secondName.add(0, "Peter"); secondName.add(1, "Malone"); // Insert elements into the Map newMap.put(1, firstName); newMap.put(2, secondName); List valueList = newMap.values() .stream() // Aforementioned A -> Stream mapping .flatMap(e -> e.stream()) .collect(Collectors.toList()); System.out.println(valueList);
Conclusion
In this tutorial, we have seen how to convert Map to List in Java in several ways with or without using Java 8 stream API.
Java 8 – Convert Map to List
For a simple Map to List conversion, just uses the below code :
package com.mkyong; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ConvertMapToList < public static void main(String[] args) < Mapmap = new HashMap<>(); map.put(10, "apple"); map.put(20, "orange"); map.put(30, "banana"); map.put(40, "watermelon"); map.put(50, "dragonfruit"); System.out.println("\n1. Export Map Key to List. "); List result = new ArrayList(map.keySet()); result.forEach(System.out::println); System.out.println("\n2. Export Map Value to List. "); List result2 = new ArrayList(map.values()); result2.forEach(System.out::println); > >
1. Export Map Key to List. 50 20 40 10 30 2. Export Map Value to List. dragonfruit orange watermelon apple banana
Java 8 – Map To List
For Java 8, you can convert the Map into a stream, process it and returns it back as a List
package com.mkyong; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class ConvertMapToList < public static void main(String[] args) < Mapmap = new HashMap<>(); map.put(10, "apple"); map.put(20, "orange"); map.put(30, "banana"); map.put(40, "watermelon"); map.put(50, "dragonfruit"); System.out.println("\n1. Export Map Key to List. "); List result = map.keySet().stream() .collect(Collectors.toList()); result.forEach(System.out::println); System.out.println("\n2. Export Map Value to List. "); List result2 = map.values().stream() .collect(Collectors.toList()); result2.forEach(System.out::println); System.out.println("\n3. Export Map Value to List. say no to banana"); List result3 = map.keySet().stream() .filter(x -> !"banana".equalsIgnoreCase(x)) .collect(Collectors.toList()); result3.forEach(System.out::println); > >
1. Export Map Key to List. 50 20 40 10 30 2. Export Map Value to List. dragonfruit orange watermelon apple banana 3. Export Map Value to List. say no to banana dragonfruit orange watermelon apple
3. Java 8 – Convert Map into 2 List
This example is a bit extreme, uses map.entrySet() to convert a Map into 2 List
package com.mkyong; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; //https://www.mkyong.com/java8/java-8-how-to-sort-a-map/ public class ConvertMapToList < public static void main(String[] args) < Mapmap = new HashMap<>(); map.put(10, "apple"); map.put(20, "orange"); map.put(30, "banana"); map.put(40, "watermelon"); map.put(50, "dragonfruit"); // split a map into 2 List List resultSortedKey = new ArrayList<>(); List resultValues = map.entrySet().stream() //sort a Map by key and stored in resultSortedKey .sorted(Map.Entry.comparingByKey().reversed()) .peek(e -> resultSortedKey.add(e.getKey())) .map(x -> x.getValue()) // filter banana and return it to resultValues .filter(x -> !"banana".equalsIgnoreCase(x)) .collect(Collectors.toList()); resultSortedKey.forEach(System.out::println); resultValues.forEach(System.out::println); > >
//resultSortedKey 50 40 30 20 10 //resultValues dragonfruit watermelon orange apple