例如我有 Foo
反对的话我有一些Foo
二维数组内的数据 Foo[][]
。我想把它转换成Set<Foo>
为了获得 Foo 唯一数据集。我怎样才能做到这一点?
最佳答案
一个简单(但不是性能最佳)的解决方案是使用 java 流:
Set<Foo> set = Arrays.stream(array)
.flatMap(Arrays::stream)
.collect(Collectors.toSet());
上面的代码片段首先创建了一个Stream<Foo[]>
与 Arrays.stream(array)
陈述。
然后它将流压平为 Stream<Foo>
第二条语句:.flatMap(Arrays::stream)
其行为与 .flatMap(arr -> Arrays.stream(arr))
相同。
最后它创建了一个 Set<Foo>
从扁平流中出来 .collect(Collectors.toSet())
.
我建议深入研究 Java 8 中引入的 Java Streaming API。它的功能远不止将 2d 数组映射到 Set 中。
<小时/>另一种方法是使用 2 个嵌套的 for 循环:
Set<Foo> set = new HashSet<>(); // or LinkedHashSet if you need a similar order than the array
for(Foo[] inner : array) {
for(Foo item : inner) {
set.add(item);
}
}
关于java - 如何将二维数组转换为Set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54230148/