3 回答

TA貢獻1802條經驗 獲得超5個贊
您可以使用的簡單方法:
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());

TA貢獻1809條經驗 獲得超8個贊
例如:
private static Stream<Example> flat(Example example) {
return Stream.concat(Stream.of(example),
example.getSubExamples().stream().flatMap(Sandbox::flat));
}
where 是定義方法的類。Sandboxflat

TA貢獻1804條經驗 獲得超2個贊
這可以通過非遞歸方式完成:
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;
}
添加回答
舉報