Tuesday, February 2, 2016

Convert HashMap to Array List

 Conver HashMap into Array List

package com.tutorials.maptolist;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapToList {

     public static void main(String[] args) {

          // Conversion Of HashMap Keys Into ArrayList
          // public abstract Set<K> keySet();

          HashMap<String, String> map = new HashMap<String, String>();
          map.put("Paras", "Chawla");
          map.put("Nonu", "Gupta");
          Set<String> set = map.keySet();
          List<String> keyList = new ArrayList<String>(set);
          System.out.println(keyList);

          // Conversion Of HashMap values Into ArrayList
          // public abstract Collection<V> values();
          Collection<String> values = map.values();
          List<String> valueList = new ArrayList<String>(values);
          System.out.println(valueList);

          // Conversion Of HashMap’s Key-Value Pairs Into ArrayList.Creating an ArrayList Of Entry objects
          // entrySet : Returns a Set view of the mappings contained in this map.
          // public abstract Set<Entry<K, V>> entrySet();

          Set<Entry<String, String>> entrySet = map.entrySet();
          ArrayList<Entry<String, String>> listOfEntry = new ArrayList<Entry<String, String>>(
                   entrySet);
          for (Entry<String, String> entry : listOfEntry)
              System.out.println(entry.getKey() + " : " + entry.getValue());

          System.out.println(listOfEntry);
     }
}
Output :
[Nonu, Paras]
[Gupta, Chawla]
Nonu : Gupta
Paras : Chawla


[Nonu=Gupta, Paras=Chawla]

No comments:

Post a Comment