我有一个Java类
class Example{
String field1;
String field2;
List<Example> subExamples;
}
在上述情况下,Example具有subExamples,而subExamples仍是示例列表。此嵌套可以是n级。我要实现的是拥有一个示例列表,即将上述对象弄平,并将所有示例收集到最终列表中(收集所有n级示例)。一种明显的方法是递归。 Java中有什么方法可以更有效地实现它。我尝试了一些Java 8概念,但它们不符合要求。
答案 0 :(得分:1)
例如:
private static Stream<Example> flat(Example example) {
return Stream.concat(Stream.of(example),
example.getSubExamples().stream().flatMap(Sandbox::flat));
}
其中Sandbox
是定义flat
方法的类。
答案 1 :(得分:1)
您可以使用的一种简单方法:
static Stream<Example> flatten(Example ex) {
if (ex.getSubExamples() == null || ex.getSubExamples().isEmpty()) {
return Stream.of(ex);
}
return Stream.concat(Stream.of(ex),
ex.getSubExamples().stream().flatMap(Main::flatten));
}
您可以将其用作
List<Example> flattened = examples.stream()
.flatMap(Main::flatten) //change class name
.collect(Collectors.toList());
答案 2 :(得分:1)
这可以以非递归的方式完成:
private Collection<Example> flatten(Example example) {
Queue<Example> work = new ArrayDeque<>();
if (example != null) {
work.offer(example);
}
Collection<Example> flattened = new ArrayList<>();
while(!work.isEmpty()) {
Example cur = work.poll();
flattened.add(cur);
cur.subExamples.forEach(work::offer);
}
return flattened;
}