Thursday, August 25, 2022

How to Convert a Map to a List in Java - Example Tutorial

Hello guys, if you are wondering how to convert a Map like HashMap or TreeMap to a List like ArrayList or LinkedList in Java then you are at the right place. Earlier, I have shared 10 examples of converting a List to Map in Java and this article, I am going to share my tip to convert a given Map to a List in Java. Map and List are two common data structures available in Java and in this article, we will see how can we convert Map values or Map keys into List in Java. The primary difference between Map (HashMap, ConcurrentHashMap, or TreeMap) and List is that Map holds two objects key and value while List just holds one object which itself is a value. 

Key in HashMap is just an add-on to find values, so you can just pick the values from Map and create a List out of it. The Map in Java also allows duplicate values which is fine with List which also allows duplicates but Map doesn't allow duplicate keys, this means you can use to store keys into a Set. 

By the way, the general requirement to convert a Map to List doesn't come as straightforward as it sounds. You often want to just get all the keys in a List or all the values in a List or all the entries in the List. 

Java's Map API or should I call the Map interface provides convenient methods like keySet() to retrieve all keys in a Set, values() to retrieve all values in a Collection and entrySet() to retrieve all entries in a Set in Java. 

You can use these utility methods to get the data you want and then you can use the same trick I shared here to convert a Set to List in Java to get a List you want. 


From Java 8 onwards, you can also use Stream API and Collector to convert a Map to List in Java. Just use these methods to get the data and then use Stream API to go through them and then finally collect the result in an unmodifiable and Immutable List using Collectors.toList() method. 




How to Convert Map into List in Java with Example 

Now that you are familiar with both Map and List, let's some code examples convert Map to list in Java. 

map to list in Java example


Map to List Example in Java

Here are few examples of converting Map to List in Java. We will see first how to convert HashMap keys into ArrayList and then HashMap values into ArrayList in Java.



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 *Converting HashMap into ArrayList in Java
 */
public class MaptoListJava {

    public static void main(String... args) {
        HashMap<String, String> personalLoanOffers = new HashMap<String, String>();
        // preparing hashmap with keys and values
        personalLoanOffers.put("personal loan by DBS", "Interest rate low");
        personalLoanOffers.put("personal loan by Standard Charted", "Interest rate low");
        personalLoanOffers.put("HSBC personal loan by DBS", "14%");
        personalLoanOffers.put("Bankd of America Personal loan", "11%");
      
        System.out.println("Size of personalLoanOffers Map: " + personalLoanOffers.size());
      
        //Converting HashMap keys into ArrayList
        List<String> keyList = new ArrayList<String>(personalLoanOffers.keySet());
        System.out.println("Size of Key list from Map: " + keyList.size());
      
        //Converting HashMap Values into ArrayList
        List<String> valueList = new ArrayList<String>(personalLoanOffers.values());
        System.out.println("Size of Value list from Map: " + valueList.size());


      
        List<Entry> entryList = new ArrayList<Entry>(personalLoanOffers.entrySet());
        System.out.println("Size of Entry list from Map: " + entryList.size());

    }
}

Output:
Size of personalLoanOffers Map: 4
Size of Key list from Map: 4
Size of Value list from Map: 4
Size of Entry list from Map: 4


That's all on Map to List Conversion in Java, as you have seen in the above example you can create a separate list for both keySet and values of HashMap as Map API return Set of keys and values of Collection in Java. As I said, from Java 8 onwards you can also use Stream API to do this conversion, you can see this example of converting Map to List using Stream in Java as well.

Let me know if you know any other way except brute force way of going through each element of Map and copying into List.



Java Tutorial you may like:

3 comments :

Anonymous said...

Converting between HashMap and List is IMHO rarely reasonable. One of main purposes of List is to define order of its elements. The indices of such a List have no meaning because of potentially random order in HashMap.
When one need to convert between HashMap and List in practical case, I guess one of these two structures is improperly chosen.
Perhaps converting from LinkedHashMap or some kind SortedMap is little bit more sensible.
Tomas Zalusky

Javin @ synchronized collection vs concurrent collection said...

Hi Tomas, I see your point.First storing data into Map and than getting back into List where primary purpose of this two are different is very rare in real life project and your point towards LinkedHashMap makes much more sense in this context.

Unknown said...

what is the use for this

Post a Comment