In this tutorial we will learn how to convert HashSet to Arraylist , Some junior developers have issues convert HashSet to Arraylist to in order to sort data or add to collection method to Arraylist .
See Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
public class Example1 {
public static void main(String args[]) {
HashSet<String> hashset = getHashSet();
}
public static HashSet<String> getHashSet(){
HashSet<String> hashset = new HashSet<String>();
// Adding elements to the HashSet
hashset.add("Item4");
hashset.add("Item2");
hashset.add("Item6");
hashset.add("Item1");
hashset.add("Item3");
hashset.add("Item5");
System.out.println("HashSet values : ");
for(String str : hashset){
System.out.println(str);
}
// Declare ArrayList to add Hashset to Arraylist
List<String> arrList = new ArrayList<String>(hashset);
System.out.println("ArrayList values : ");
for(String temp : arrList){
System.out.println(temp);
}
//sort arrayList
Collections.sort(arrList);
System.out.println("After sort Arraylist : ");
for(String temp : arrList){
System.out.println(temp);
}
return hashset;
}
}
//result :
HashSet values :
Item1
Item2
Item5
Item6
Item3
Item4
ArrayList values :
Item1
Item2
Item5
Item6
Item3
Item4
After sort Arraylist :
Item1
Item2
Item3
Item4
Item5
Item6
Subscribe to:
Post Comments (Atom)
EmoticonEmoticon