Converting one Collection to Another
Converting one collection to another is very frequent requirement of java applications. One may want to convert a Map to List, Set to List, List to Set etc. Here in this Collection conversion tutorial, we will see, how to convert a HashMap to List with example code.
The very first point to note before considering the conversion of HaspMap to List is that we want the value objects of HashMap to be present in the ArrayList. The program we will write will do so.
package com.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/** This class is a Java tutorial for collection conversion in Java
*
* @author Extreme Java
*/
public class Test{
/** This method shows how to use for converting HashMap to ArrayList in Java
*
* @param args
*/
public static void main(String[] args) {
HashMap hm = new HashMap();
ArrayList al = new ArrayList();
hm.put("a", "1");
hm.put("b", "2");
hm.put("c", "3");
Set s = hm.keySet();
System.out.println("Printing the map");
for (Iterator iterator = s.iterator(); iterator.hasNext();) {
String str = (String) hm.get(iterator.next());
System.out.println(str);
al.add(str);
}
System.out.println("Printing the arraylist");
for (Iterator iterator = al.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
}
}
}
output:
Printing the map
2
3
1
Printing the arraylist
2
3
1
But there is a better for doing the same job as shown below:
package com.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/** This class is a Java tutorial for collection conversion in Java
*
* @author Extreme Java
*/
public class Test{
/** This method shows how to use for converting HashMap to ArrayList in Java
*
* @param args
*/
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put("a", "1");
hm.put("b", "2");
hm.put("c", "3");
ArrayList al = new ArrayList(hm.values());
for (Iterator iterator = al.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
}
}
} output:
2
3
1
The output first prints the contents of hashmap by iterating on the keyset and then we show the contents of ArrayList which is built by using the value objects of the HashMap class.
No comments:
Post a Comment