Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving data from a HashSet to ArrayList in Java

Tags:

I have the following Set in Java:

Set< Set<String> > SetTemp = new HashSet< Set<String> >(); 

and I want to move its data to an ArrayList:

ArrayList< ArrayList< String > > List = new ArrayList< ArrayList< String > >); 

Is it possible to do that ?

like image 581
Ghadeer Avatar asked Nov 29 '12 18:11

Ghadeer


People also ask

How do I copy a HashSet to an array?

There are two ways of converting HashSet to the array: Traverse through the HashSet and add every element to the array. To convert a HashSet into an array in java, we can use the function of toArray().

Can we have HashSet of ArrayList in Java?

ArrayList: In Java, ArrayList can have duplicates as well as maintains insertion order. HashSet: HashSet is the implementation class of Set. It does not allow duplicates and uses Hashtable internally.

Can we convert set to ArrayList in Java?

We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.


2 Answers

Moving Data HashSet to ArrayList

Set<String> userAllSet = new HashSet<String>(usrAllTemp); List<String> usrAll = new ArrayList<String>(userAllSet); 

Here usrAllTemp is an ArrayList, which has some values. Same Way usrAll(ArrayList) getting values from userAllSet(HashSet).

like image 191
abhishek ringsia Avatar answered Oct 15 '22 19:10

abhishek ringsia


You simply need to loop:

Set<Set<String>> setTemp = new HashSet<Set<String>> (); List<List<String>> list = new ArrayList<List<String>> (); for (Set<String> subset : setTemp) {     list.add(new ArrayList<String> (subset)); } 

Note: you should start variable names in small caps to follow Java conventions.

like image 21
assylias Avatar answered Oct 15 '22 21:10

assylias