简体   繁体   English

如何转换列表<set<string> &gt; 列出<list<string> &gt; 在 java 中? </list<string></set<string>

[英]How to convert List<Set<String>> to List<List<String>> in java?

How can we convert List<Set> to List<List> in java easily?我们如何轻松地将 java 中的 List<Set> 转换为 List<List>? Context: I came across this issue where I have generated List<Set> while in function return expects List<List>.上下文:我遇到了这个问题,我在 function 中生成了 List<Set>,返回需要 List<List>。

Do you care about order in the Set s?你关心Set中的顺序吗? If you do, you'll have to make sure you don't have them as Sets in the first place.如果你这样做了,你必须首先确保你没有将它们作为 Sets。 If you don't, you can use the Java 8+ streams API:如果你不这样做,你可以使用 Java 8+ 个流 API:

list.stream().map(ArrayList::new).collect(Collectors.toList());

Or a for loop.或者一个for循环。

To convert from a Set to a List, you can simply do new ArrayList<>(mySet) .要将 Set 转换为 List,您只需执行new ArrayList<>(mySet) So you can do something like:因此,您可以执行以下操作:

Set<String> set1 = new HashSet<>(Arrays.asList("a", "b"));
Set<String> set2 = new HashSet<>(Arrays.asList("c", "d"));
List<List<String>> result = new ArrayList<List<String>>();
List<Set<String>> listOfSets = new ArrayList<>();
listOfSets.add(set1);
listOfSets.add(set2);
for (Set<String> set : listOfSets) {
    result.add(new ArrayList<>(set));
}
System.out.println(result);

Output: [[a, b], [c, d]] Output: [[a, b], [c, d]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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