有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java迭代嵌套列表(任意深度)

如何迭代嵌套列表(任意深度)?我有以下结构

Com 1
    Com 2
        Com 55
            Com 551
            Com 552
        Com 56
        Com 57
            Com 66
            Com 67
                Com 99
    Com 3
        Com 33
        Com 34
        Com 35
    Com 4
        Com 41
        Com 42
            Com 421
            Com 423

我想用层次结构将数据导出到txt文件。如何检测何时应添加“空间”以形成层次结构

@Entity
public class Company {
    private Long id;
    private String name;
    private List<Company> children = new ArrayList<>();


    public Company() {
    }
    
    //getters and setters
    
    public Stream<Company> flattened() {
        return Stream.concat(
                Stream.of(this),
                children.stream().flatMap(Company::flattened));
    }
}

共 (3) 个答案

  1. # 1 楼答案

    使用Level方法进行展平以生成对流(公司及其深度):

    public Stream<Pair<Integer, Company>> flattenedWithDepth(int depth) {
        return Stream.concat(
                Stream.of(new Pair<>(depth, this)),
                children.stream().flatMap(c -> c.flattenedWithDepth(depth+1)));
    } 
    

    然后,您可以按照需要的方式打印所有流元素:

    comp.flattenedWithDepth(1)
        .forEach(p ->
            {for (int i=0; i < p.getKey(); i++) 
                System.out.print(" ");
             System.out.println("Com " + p.getValue().getId());
            });  
    
  2. # 2 楼答案

    假设您没有循环公司引用(因此没有子公司指向其父公司之一),您可以这样递归地执行此操作:

    public static void print(Company company, int depth) {
            for (int i = 0; i < depth; i++) {
                System.out.print(" ");
            }
            System.out.println(company.getName());
            for (Company child : company.getChildren()) {
                print(child, depth + 1);
            }
    }
    
  3. # 3 楼答案

    水流进近

    @Entity
    public class Company {
    ...
        public Stream<String> indentedNames() {
            return indentedNames(0);
        }
    
        private Stream<String> indentedNames(int level) {
            return Stream.concat(
                    Stream.of(" ".repeat(level) + this.getName()),
                    children.stream().flatMap(c -> c.indentedNames(level + 1)));
        }
    ...
    }
    
        public static void main(String[] args) {
            Company company1 = new Company("1");
            Company company2 = new Company("2");
            Company company3 = new Company("3");
            Company company4 = new Company("4");
            Company company5 = new Company("5");
            Company company6 = new Company("6");
            Company company7 = new Company("7");
            company1.setChildren(List.of(company2, company3));
            company2.setChildren(List.of(company4, company5));
            company4.setChildren(List.of(company6, company7));
            company1.indentedNames().forEach(System.out::println);
        }