java 需要将孩子与父母Map

euoag5mw  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(113)
name    id      parentId
A       1           0   
B1      2           1   
B2      3           1   
C1      4           2   
C2      5           3   
D1      6           5

上面是一个表我用来保持父子关系,现在与上述数据,我需要框架的父母和他们的查尔兹在java树格式的列表,一个解决方案是使用递归,有没有其他最好的解决方案,以找出孩子和他们的父母
预期输出格式:

List<Person> parentList;

    Class Person{
        String name;
        List<Person> childs;
    }
ulydmbyx

ulydmbyx1#

以下是使用Hashmap的示例:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Relation> relations = Arrays.asList(
                new Relation("A", 1, 0),
                new Relation("B1", 2, 1),
                new Relation("B2", 3, 1),
                new Relation("C1", 4, 2),
                new Relation("C2", 5, 3),
                new Relation("D1", 6, 5)
        );

        List<Person> parentList = buildParentChildList(relations);
        printPersons(parentList, 0);
    }

    public static List<Person> buildParentChildList(List<Relation> relations) {
        Map<Integer, Person> personMap = new HashMap<>();
        Map<Integer, List<Person>> childMap = new HashMap<>();

        for (Relation relation : relations) {
            Person person = new Person(relation.name);
            personMap.put(relation.id, person);
            childMap.putIfAbsent(relation.parentId, new ArrayList<>());
            childMap.get(relation.parentId).add(person);
        }

        for (Person person : personMap.values()) {
            person.childs = childMap.getOrDefault(person.id, Collections.emptyList());
        }

        return childMap.get(0);
    }

    public static void printPersons(List<Person> persons, int level) {
        for (Person person : persons) {
            System.out.println("  ".repeat(level) + person.name);
            printPersons(person.childs, level + 1);
        }
    }
}

class Relation {
    String name;
    int id;
    int parentId;

    Relation(String name, int id, int parentId) {
        this.name = name;
        this.id = id;
        this.parentId = parentId;
    }
}

class Person {
    String name;
    int id;
    List<Person> childs;

    Person(String name) {
        this.name = name;
    }
}

希望有帮助,祝你好运。

相关问题