DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Converting Java Maps to Lists

Converting Java Maps to Lists

You're probably no stranger to converting between data structures, so here are a number of ways you can do it using tools brought to us in Java 8.

John Thompson user avatar by
John Thompson
·
May. 14, 18 · Tutorial
Like (34)
Save
Tweet
Share
113.04K Views

Join the DZone community and get the full member experience.

Join For Free

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 Lists

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 Lists

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 Maps to Lists Using Java 8 Streams

If you are into a more 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 a stream of Map entries to List.

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


The stream() method returns 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 a 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 a 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:

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


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

Converting Generic Maps to Lists Using Streams and Java Lambdas

Until now, I've shown how to use method references with streams to perform conversions of Maps to Lists.

I personally prefer method references over lambda expressions because I find them to be clear and concise.

Also, when using collections, 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 a 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.

Java (programming language) unit test Stream (computing) JUnit

Published at DZone with permission of John Thompson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • ChatGPT: The Unexpected API Test Automation Help
  • Top Three Docker Alternatives To Consider
  • Select ChatGPT From SQL? You Bet!
  • Express Hibernate Queries as Type-Safe Java Streams

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: