Java将Set <Set <String >>转换为List <List <String >>

Cod*_*lus 2 java collections list set

在Java中,我无法从a转换Set<Set<String>>为a List<List<String>>,然后使用的内容填充此列表Set<Set<String>>

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

InP*_*uit 6

您无法实例化List接口的实例,您需要使用其中一个类似ArrayList的实现.然后,您可以遍历treeComps中的外部集合,为每个内部集合创建一个新的ArrayList,在此ArrayList上调用addAll,然后将列表添加到组件中.

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 );
}
Run Code Online (Sandbox Code Playgroud)