Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Sunday

How to convert a map to list in Java with example

How to convert a map to list in Java with example

Before doing this you must have clear idea of List and Map in Java. List is an Interface implementing the Collection Interface.List allows duplicate values.Some Classes implementing List Interfaces are ArrayList,LinkedList etc.Map is not a Collection.Some Classes implementing the Map Interfaces are HashMap,TreeMap etc.

Logic:
  1. First we have to convert the Map into a Set using entryset.
  2. Second we have to convert Set into List.
Example:

public class HelloWorld{

public static void main(String[] args) {
HashMap<String, Integer> mapOne = new HashMap<String, Integer>();

mapOne.put("one", 1);
mapOne.put("two", 2);
mapOne.put("three", 3);
mapOne.put("four", 4);
mapOne.put("five", 5);
        
        Set<Entry<String, Integer>> set = mapOne.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
        Iterator<Entry<String, Integer>> it = list.iterator();
        
        while (it.hasNext()) {
            Entry<String, Integer> entry = it.next();
            System.out.println("Map Converted to List : " + entry);
        }
}
}


Output:
Map Converted to List : two=2
Map Converted to List : five=5
Map Converted to List : one=1
Map Converted to List : four=4
Map Converted to List : three=3

No comments:

Post a Comment