Sunday, December 31, 2017

How to Convert a Map to a List in Java Example

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 addon to find values, so you can just pick the values from Map and create a List out of it. The map in Java allows duplicate value which is fine with List which also allows duplicates but Map doesn't allow duplicate key.

How to Convert Map into List in Java with 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

Oracle Java Prep, Oracle Java Guides, Oracle Java Learning, Oracle Java Study Materials

That's all on Map to List Conversion in Java , as you seen in above example you can create a separate list for both keySet and values Collection in Java. let me know if you know any other way except brute force way of going through each element of Map and copying into List.

Related Posts

0 comments:

Post a Comment