Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert Set<Set<String>> to List<List<String>>

In Java I am having trouble converting from a Set<Set<String>> to a List<List<String>> and then populating this list with the contents of the Set<Set<String>>

Here is my code:

Set<Set<String>> treeComps = compExtractor.transform(forest); // fine
List<List<String>> components = new List<List<String>>();     // does not work
components.addAll(treeComps);                                 // does not work
like image 238
CodeKingPlusPlus Avatar asked Mar 07 '26 06:03

CodeKingPlusPlus


2 Answers

You can't instantiate an instance of the List interface, you need to use one of the implementations like ArrayList. Then you can iterate over the outer set in treeComps, create a new ArrayList for each inner set, call addAll on this ArrayList and then add the list to components.

List<List<String>> components = new ArrayList<List<String>>();
for( Set<String> s : treeComps )
{
  List<String> inner = new ArrayList<String>();
  inner.addAll( s );
  components.add( inner );
}
like image 139
InPursuit Avatar answered Mar 08 '26 19:03

InPursuit


I think only way is iterate over outer set. Get inner set and user new ArrayList<String>(innerSet)

Add above result list to outerlist.

like image 34
kosa Avatar answered Mar 08 '26 18:03

kosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!