在 java 中展平嵌套的 N 级嵌套对象

我有一个java类

class Example{
   String field1;
   String field2;
   List<Example> subExamples;    
}

在上面的场景中,示例具有子示例,这又是示例列表。此嵌套可以是 n 级。我想实现的是有一个示例列表,即平展上述对象并将所有示例收集到最终列表中(收集所有n级示例)。一种明显的方法是递归。在Java中,有什么方法可以更有效地实现它。我尝试了一些java 8概念,但它们不符合要求。


汪汪一只猫
浏览 147回答 3
3回答

慕后森

您可以使用的简单方法:static Stream<Example> flatten(Example ex) {&nbsp; &nbsp; if (ex.getSubExamples() == null || ex.getSubExamples().isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; return Stream.of(ex);&nbsp; &nbsp; }&nbsp; &nbsp; return Stream.concat(Stream.of(ex),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ex.getSubExamples().stream().flatMap(Main::flatten));}您可以将其用作List<Example> flattened = examples.stream()&nbsp; &nbsp; &nbsp; &nbsp; .flatMap(Main::flatten) //change class name&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());

海绵宝宝撒

例如:private static Stream<Example> flat(Example example) {&nbsp; &nbsp; return Stream.concat(Stream.of(example),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;example.getSubExamples().stream().flatMap(Sandbox::flat));}where 是定义方法的类。Sandboxflat

慕婉清6462132

这可以通过非递归方式完成:private Collection<Example> flatten(Example example) {&nbsp; Queue<Example> work = new ArrayDeque<>();&nbsp; if (example != null) {&nbsp; &nbsp; work.offer(example);&nbsp; }&nbsp; Collection<Example> flattened = new ArrayList<>();&nbsp; while(!work.isEmpty()) {&nbsp; &nbsp; Example cur = work.poll();&nbsp; &nbsp; flattened.add(cur);&nbsp; &nbsp; cur.subExamples.forEach(work::offer);&nbsp; }&nbsp; return flattened;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java