【问题标题】:Get selected object from the tree based on passing argument根据传递的参数从树中获取选定的对象
【发布时间】:2017-12-09 22:59:52
【问题描述】:

所以我有这个 Person 对象。每个人都有人对象列表等等..

public class Person {
    ....
    private List<Person> people = new ArrayList<>();

    ....

    public List<Person> getPeople() {
        return people;
    }

    public void setPeople(List<Person> people) {
        this.people = people;
    }

我已经使用以下代码得到了最大部门的答案,答案是我得到的任何 int 减去 1

public static int maxDepth(Person p) {
        int maxChildrenDepth = 0;
        for (Person c: p.getPeople()) {
            maxChildrenDepth = Math.max(maxChildrenDepth, maxDepth(c));
        }
        return 1 + maxChildrenDepth;
    }

所以如果我将 Person 对象和 int 传递给方法,比如说 getPersonLevel(List allPerson, 1) ,我应该得到 List 内所有蓝色框的 Person 对象,如果我输入 2,我应该得到所有对象在红色框的列表中等等,具体取决于 int 参数..我如何做到这一点?任何帮助表示赞赏。

【问题讨论】:

    标签: java oop collections java-8 depth-first-search


    【解决方案1】:

    与其将人作为方法的参数传递,为什么不制作Person类的maxDepthgetPersonLevel方法?

    结果你会得到:

    public class Person {
    
        private Set<Person> people = new HashSet<>();
    
        public Set<Person> getPeople() {
            return people;
        }
    
        public void setPeople(Set<Person> people) {
            this.people = people;
        }
    
        public int maxDepth() {
            int maxChildrenDepth = 0;
            for (Person prs : people) {
                maxChildrenDepth = Math.max(maxChildrenDepth, prs.maxDepth());
            }
            return 1 + maxChildrenDepth;
      }
    
      public Set<Person> getPersonLevel(int depth) {
          Set<Person> ppl = new HashSet<>();
          ppl.addAll(gatherEmployees(ppl, depth));
          return ppl;
      }
    
      private Set<Person> gatherEmployees(Set<Person> ppl, int depth) {
          if (depth - 1 > 0 && people != null) {
              people.forEach(prs -> ppl.addAll(prs.gatherEmployees(ppl, depth - 1)));
          }
          return people;
      }
    }
    

    【讨论】:

    • 它不起作用 --> getPersonLevel 不起作用,因为它返回空
    • 抱歉,我是即时写的,没有花时间测试代码。我编辑了我的答案,这个版本已经过测试,我可以向你保证它有效!
    【解决方案2】:

    这个有效!

    public Set<Person> getPersonLevel(Person person, int depth) {
           Set<Person> aList = new HashSet<>();
    
           if (depth == 1)
               aList.addAll(person.getPeople());
    
           if (depth > 1){
               for (Person pp : person.getPeople()) {
                       aList.addAll(getPersonLevel(pp, depth -1));
               }
           }
           return aList;
        }
    

    【讨论】:

      猜你喜欢
      • 2015-11-11
      • 2020-06-10
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多