断毫残墨 2023-02-07 10:19 采纳率: 33.3%
浏览 33

java多个list联合循环递归如何实现

有一个需求,有3个全局缓存的list集合
比如 ACache,BCache,CCache三个list集合,三个集合相互关联,需要递归查询出指定条件的数据
1. 过滤出A的id大于5的数据
2. 通过A的id关联B的aid查出B的数据
3. 然后在通过B的id关联bid查询出C的数据
4 .如果C的aid不为0时,需要递归查询,重复执行1-4步

具体代码结构如下

import java.util.ArrayList;
import java.util.List;

public class Main {

    private static List<A> ACache = new ArrayList<>();
    private static List<B> BCache = new ArrayList<>();
    private static List<C> CCache = new ArrayList<>();

    /*初始化数据*/
    static {
        for (int i = 1; i <= 10; i++) {
            ACache.add(new A(i, "a" + i));
            for (int j = 1; j <= 3; j++) {
                BCache.add(new B(j, "b" + j, i));
                for (int k = 1; k <= 3; k++) {
                    if(i==10) {
                        CCache.add(new C(k, "c" + k, j, 0));
                    }else{
                        CCache.add(new C(k, "c" + k, j, 11));
                    }
                }
            }
        }

        ACache.add(new A(11, "a" + 11));
        BCache.add(new B(100, "b" + 100,11));
        BCache.add(new B(101, "b" + 101,11));

        CCache.add(new C(1000, "c" + 1000, 100, 0));
        CCache.add(new C(1001, "c" + 1001, 100, 0));
        CCache.add(new C(1002, "c" + 1002, 101, 0));
        CCache.add(new C(1003, "c" + 1003, 101, 0));
    }


    public static void main(String[] args) {
        // 1. 过滤出A的id大于5的数据
        // 2. 通过A的id关联B的aid查出B的数据
        // 3. 然后在通过B的id关联bid查询出C的数据
        // 4 .如果C的aid不为0时,需要递归查询,重复执行1-4步
        List<A> AList = new ArrayList<>();
        List<B> BList = new ArrayList<>();
        List<C> CList = new ArrayList<>();
        ACache.stream().filter(item -> item.id>5).forEach(AList::add);
        
        getData(AList,BList,CList);
        
        System.out.println(AList);
        System.out.println(BList);
        System.out.println(CList);

    }

    private static void getData(List<A> aList, List<B> bList, List<C> cList) {
        // 多个list联合递归如何实现
    }

    public static class A {
        public int id;
        public String name;

        public A(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }

    public static class B {
        public int id;
        public String name;
        public int aid;

        public B(int id, String name, int aid) {
            this.id = id;
            this.name = name;
            this.aid = aid;
        }
    }

    public static class C {
        public int id;
        public String name;
        public int bid;
        public int aid;

        public C(int id, String name, int bid, int aid) {
            this.id = id;
            this.name = name;
            this.bid = bid;
            this.aid = aid;
        }
    }

}


  • 写回答

3条回答 默认 最新

  • 於黾 2023-02-07 10:31
    关注

    没看懂你这要求跟递归有什么关系
    你完全可以用循环
    或者先把每一步筛出来的集合缓存起来,然后用结果集继续后续的步骤
    而不是每次都要从头开始筛

    评论

报告相同问题?

问题事件

  • 修改了问题 2月7日
  • 创建了问题 2月7日