【问题标题】:Get all leaves elements of a recursive nested structure data in Java [duplicate]在Java中获取递归嵌套结构数据的所有叶子元素[重复]
【发布时间】:2022-02-11 02:17:56
【问题描述】:

如何获取递归嵌套结构数据的所有叶子元素?

public class Item {
    private String id;
    private List<Item> items;
}

示例

    A
      - AA
        - aa1
      - AB
        - ab1
          - abab1
      - a1

结果

在结果中,我只需要获取以下元素列表 [aa1, abab1, a1]

【问题讨论】:

标签: java


【解决方案1】:

像这样适应Item

public static class Item {
    private final String id;
    private final List<Item> items;

    public Stream<Item> getLeaves() {
        if (items == null || items.isEmpty()) {
            return Stream.of(this);
        }
        return items.stream()
            .flatMap(Item::getLeaves);
    }

}

然后您可以将其用作:

final var item = new Item(
    "A",
    List.of(
        new Item("AA",
            List.of(new Item("aa1"))
        ),
        new Item("AB",
            List.of(new Item("ab1",
                List.of(new Item("abab1")))
            )
        ),
        new Item("a1")
    )
);

final var leaves = item.getLeaves()
    .map(Item::getId)
    .collect(Collectors.toList());

System.out.println(leaves);

注意:为简洁起见,省略了构造函数和 getter

【讨论】:

    【解决方案2】:

    你可以用递归的方式很容易地做到这一点:

    public static List<Item> findLeaves(Item rootItem){
        List<Item> leaves = new ArrayList<>();
        recursivelyCollectLeaves(leaves, rootItem);
        return leaves;
    }
    
    private static void recursivelyCollectLeaves(List<Item> leaves, Item actualItem){
        if(actualItem.getItems().isEmpty()){
            //No children, the actual item is a leaf
            leaves.add(actualItem);
        }
        else{
            for(Item child : actualItem.getItems()){
                recursivelyCollectLeaves(leaves, child);
            }
        }
    }
    

    PS:为了使这段代码正常工作,请注意我在 Item 类中添加了 getter。

    【讨论】:

      【解决方案3】:

      尝试将此方法添加到类中:

      public List<Item> getLeaves() {
          ArrayList<Item> list = new ArrayList<>();
          if (items.size() == 0) {
              list.add(this);
          } else {
              for (Item item : items) {
                  list.addAll(item.getLeaves());
              }
          }
          return list;
      }
      

      它只是检查自己是否是一片叶子。如果是,则返回自身,如果不是,则返回其子节点的所有叶子。

      【讨论】:

      • 考虑到这个问题被标记为java-stream,基于Stream的实现会受到欢迎,否则它只是How to get all leaf nodes of a tree?的重复
      • @DidierL,我和 Reddragio 的答案发布时标签尚未添加
      • 检查历史记录,它们在修订版 1 上 ? 事实上,理想情况下,您应该在任何情况下都查找重复项,如果您没有注意到标签,则将问题标记为此类。无论如何,不​​用担心。
      • 最后看来这个问题真的是重复的,所以就这样关闭了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 2013-11-17
      • 2018-09-12
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多