Home > Enterprise >  Hashmap implemented as a family tree with linked list Java
Hashmap implemented as a family tree with linked list Java

Time:12-26

I have a question regarding a Hashmap that is implemented as a Family tree which looks like this. The key value of the Hashmap is the first name of the person and the value is from the class Person, which contains again the first name, the sex and an Arraylist with the children. The children are again from type person. I want to find a way to make a function, which should return an float array with two fields, in the first field the maximum of children a person has from all persons and the mean of children of all persons. Should look like this:

float[] describe(Map<String, Person> m) {
}

This is the Hashmap: (already filled with keys and values and there is also a link between them and the children)

Map<String, Person> allPersons = new HashMap<String, Person>();

This is the class Person:

class Person {
    String name;
    String sex;
    List<Person> children;

    public Person(String name, String sex) {
        this.name = name;
        this.sex = sex;
        this.children = new ArrayList<Person>();
    }
}

My question is how can u iterate through the Hashmap and also get the amount of children every person has.

CodePudding user response:

It may be convenient to use Stream API and its Collectors::summarizingInt with regard to the size of children list per Person:

float[] describe(Map<String, Person> m) {
    IntSummaryStatistics stats = m.values()
        .stream() // Stream<Person>
        .collect(Collectors.summarizingInt(p -> p.getChildren().size()));

    return new float[]{ stats.getMax(), (float) stats.getAverage()};
}

CodePudding user response:

If you don't care about the size of the grandchildren, you can use stream with summaryStatistics

Map<String, Person> m = Map.of(...);
IntSummaryStatistics stats = m.values().stream()
        .mapToInt(person -> person.children.size())
        .summaryStatistics();
float[] s = {stats.getMax(), (float) stats.getAverage()};

Iterative solution:

float max = 0, sum = 0;
for (Person person : m.values()) {
    max = Math.max(person.children.size(), max);
    sum  = person.children.size();
}

float[] s = {max, sum / m.values().size()};
  • Related