简体   繁体   中英

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

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 );
}

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

Add above result list to outerlist.

Something like this...

Set<Set<String>> treeComps = compExtractor.transform(forest);
List<List<String>> lists = new ArrayList<List<String>>();
for (Set<String> singleSet : treeComps) {
    List<String> singleList = new ArrayList<String>();
    singleList.addAll(singleSet);
    lists.add(singleList);
}
List<List<String>> components = new Vector<List<String>>();
List<String> n;
for( Set<String> s : trerComps ) {
   n = new Vector<String>();
   n.addAll( s );
   components.add( n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM