2

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

4 Answers 4

6

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 );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why not just components.add(new ArrayList<String>(s))?
2

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

Add above result list to outerlist.

Comments

1

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

Comments

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

2 Comments

It's not possible to instantiate a List... It's an interface!
some commentary would help the OQ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.