Converting Java Map to List

Converting Java Map to List

4 Comments

Converting a Java Map to a List is a very common task. Map and List are common data structures used in Java. A Map is a collection of key value pairs. While a List is an ordered collection of objects in which duplicate values can be stored.

In this post, I will discuss different ways to convert a Map to a List.

For the example code in this post, I’ll provide JUnit tests. If you are new to JUnit, I suggest you go through my series on Unit Testing with JUnit.

Converting Map Keys to List

The Map class comes with the keyset() method that returns a Set view of the keys contained in the map. The code to convert all the keys of a Map to a Set is this.

public List<Integer> convertMapKeysToList(Map<Integer,String> map){
    List<Integer> listOfKeys = new ArrayList(map.keySet());
    return listOfKeys;
}

Here is the JUnit test code.

package springframework.guru;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hamcrest.collection.IsEmptyCollection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.*;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;

public class MapToListConverterTest {
    MapToListConverter mapToListConverter;
    Map<Integer, String> countryDialCodeMap;

    @Before
    public void setUp() throws Exception {
        mapToListConverter = new MapToListConverter();
        countryDialCodeMap = new HashMap<>();
        countryDialCodeMap.put(1, "United States");
        countryDialCodeMap.put(44, "United Kingdom");
        countryDialCodeMap.put(27, "South Africa");
        countryDialCodeMap.put(33, "France");
        countryDialCodeMap.put(55, "Brazil");
    }

    @After
    public void tearDown() throws Exception {
        mapToListConverter=null;
        countryDialCodeMap = null;
    }

    @Test
    public void convertMapKeysToList(){
        List<Integer> convertedListOfKeys = mapToListConverter.convertMapKeysToList(countryDialCodeMap);
        assertThat(convertedListOfKeys, not(IsEmptyCollection.empty()));
        assertThat(convertedListOfKeys, hasSize(5));
        assertThat(convertedListOfKeys, containsInAnyOrder(1,33,44,27,55));
        printList(convertedListOfKeys);
    }

    private void printList(List list){
        list.stream().forEach(System.out::println);
    }
}

The output on running the test in IntelliJ is this.
Test Output Java Map Key To List

Converting Map Values to List

You use the values() method of Map to convert all the values of Map entries into a List.

Here is the code to convert Map values to a List.

public List<String> convertMapValuesToList(Map<Integer,String> map){
    List<String> listOfValues = new ArrayList(map.values());
    return listOfValues;
}

Here is the Junit test code.

@Test
public void convertMapValuesToList(){
    List<String> convertedListOfValues = mapToListConverter.convertMapValuesToList(countryDialCodeMap);
    assertThat(convertedListOfValues, not(IsEmptyCollection.empty()));
    assertThat(convertedListOfValues, hasSize(5));
    assertThat(convertedListOfValues, containsInAnyOrder("United States", "United Kingdom", "Brazil", "South Africa", "France"));
    printList(convertedListOfValues);
}

The output on running the test in IntelliJ is this.
Test Output Map Values to List

Converting Map to List using Java 8 Streams

If you are into functional programming style, you can use streams introduced in Java 8, along with some utility classes like Collectors, which provides several useful methods to convert stream of Map entries to List.

public List<Integer> convertMapKeysToListWithStream(Map<Integer,String> map){
 List<Integer> listOfKeys2 = map.keySet().stream().collect(Collectors.toList());
    return listOfKeys2;
}

The stream() method return a stream of the keys from the Set of the map keys that Map.keySet() returns. The collect() method of the Stream class is called to collect the results in a List.

The Collectors.toList() passed to the collect() method is a generalized approach. You can collect elements of Stream in specific collection, such as ArrayList, LinkedList, or any other List implementation. To do so, call the toColection() method, like this.

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

Here is the JUnit test code.

@Test
public void convertMapKeysToListWithStream(){
    List<Integer> convertedListOfKeys = mapToListConverter.convertMapKeysToListWithStream(countryDialCodeMap);
    assertThat(convertedListOfKeys, not(IsEmptyCollection.empty()));
    assertThat(convertedListOfKeys, hasSize(5));
    assertThat(convertedListOfKeys, hasItems(33,27));
    assertThat(convertedListOfKeys, containsInAnyOrder(1,33,44,27,55));
    printList(convertedListOfKeys);
}

The JUnit test output in IntelliJ is this.
Test Output Java Map Keys To List with Java 8 Streams

Converting Map values to List using streams is similar. You only need to get the stream of Map values that map.values() return, like this

public List<String> convertMapValuesToListWithStream(Map<Integer,String> map){
    List<String> listOfValues = map.values().stream().collect(Collectors.toCollection(ArrayList::new));
    return listOfValues;
}

The test code is this.

@Test
public void convertMapValuesToListWithStream(){
    List<String> convertedListOfValues = mapToListConverter.convertMapValuesToListWithStream(countryDialCodeMap);
    assertThat(convertedListOfValues, not(IsEmptyCollection.empty()));
    assertThat(convertedListOfValues, hasSize(5));
    assertThat(convertedListOfValues, hasItems("United States","France"));
    assertThat(convertedListOfValues, containsInAnyOrder("United States", "United Kingdom", "Brazil", "South Africa", "France"));
    printList(convertedListOfValues);
}

The test output in IntelliJ is this.
Test Output Map Values To List with Stream

Converting Generic Map to List using Stream and Java Lambdas

Till now I showed using method reference with stream to perform conversion of Map to List.
I personally prefer method reference over lambda expressions because I find them clear and concise.
Also, when using collection, you will typically use generic collections and perform conversions between them.

For such collections, you can use streams with lambda expressions, like this.

public static<K, V> List<K> convertGenericMapKeysToListWithStreamLambda(Map<K,V> map){
    List<K> keyList = new ArrayList<>();
    map.entrySet().stream().forEach(entry->
      {keyList.add(entry.getKey());
       });
    return keyList;
}

The code to use method reference is this.

public static<K, V> List<V> convertGenericMapValuesToListWithStreamMethodReference(Map<K,V> map){
    List<V> keyList = new ArrayList<>();
    map.values().stream().forEach(keyList::add);
    return keyList;
}

Here is the JUnit test code.

@Test
public void convertGenericMapKeysToListWithStreamLambda(){
    List<Integer> convertedListOfKeys = mapToListConverter.convertGenericMapKeysToListWithStreamLambda(countryDialCodeMap);
    assertThat(convertedListOfKeys, not(IsEmptyCollection.empty()));
    assertThat(convertedListOfKeys, hasSize(5));
    assertThat(convertedListOfKeys, hasItems(33,27));
    assertThat(convertedListOfKeys, containsInAnyOrder(1,33,44,27,55));
    printList(convertedListOfKeys);
}

@Test
public void convertGenericMapKeysToListWithStreamMethodReference(){
    List<String> convertedListOfValues = mapToListConverter.convertGenericMapValuesToListWithStreamMethodReference(countryDialCodeMap);
    assertThat(convertedListOfValues, not(IsEmptyCollection.empty()));
    assertThat(convertedListOfValues, hasSize(5));
    assertThat(convertedListOfValues, hasItems("United States","France"));
    assertThat(convertedListOfValues, containsInAnyOrder("United States", "United Kingdom", "Brazil", "South Africa", "France"));
    printList(convertedListOfValues);
}

The JUnit test output in IntelliJ is this.

About jt

    You May Also Like