Senin, 24 Maret 2014

How to Convert Map to 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. Primary difference between Map (HashMap, ConcurrentHashMap or TreeMap) and List is that Map holds two object 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. 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



HashMap,Map to Arraylist in java with ExampleMap 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 than 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 personalLoanOffers = new HashMap();


        // 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 keyList = new ArrayList(personalLoanOffers.keySet());


        System.out.println("Size of Key list from Map: " + keyList.size());


      


        //Converting HashMap Values into ArrayList


        List valueList = new ArrayList(personalLoanOffers.values());


        System.out.println("Size of Value list from Map: " + valueList.size());








      


        List entryList = new ArrayList(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 seen in above example you can create 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.




Java Tutorial you may like:


































Source:http://javarevisited.blogspot.com/2011/12/how-to-convert-map-to-list-in-java.html

Tidak ada komentar:

Posting Komentar