#275 Filtering and Sorting Persons and Children

Companies:
Sberbank
Themes:
JavaStreams & LambdasPractice

The following class is given:

import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        var personList = init();
        printList(personList);

    }

        private static void printList(List list) {
        System.out.println(list.stream()
            .map(Object::toString)
            .collect(Collectors.joining("\n")));
    }

        private static List<Person> init() {
        return List.of(
            new Main.Person("Alexey", List.of(
                new Main.Child("Albina", 3),
                new Child("Arseniy", 8),
                new Child("Alexander", 15))),
            new Main.Person("Grigory", List.of()),
            new Main.Person("Dmitry", List.of(
                new Main.Child("Darya", 1),
                new Child("Daniil", 5))),
            new Main.Person("Boris", List.of(
                new Main.Child("Bogdan", 9))),
            new Main.Person("Victoria", List.of(
                new Main.Child("Vladimir", 4),
                new Child("Varvara", 7),
                new Child("Valeria", 12))),
            new Main.Person("Elena", List.of(
                new Main.Child("Evgeny", 11))));
    }

    public static class Child {

        private String name;
        private Integer age;

        Child(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public Integer getAge() {
            return age;
        }

        @Override
        public String toString() {
            return name + " - " + age;
        }

    }

    public static class Person {

        private String name;
        private List<Child> children;

        Person(String name, List<Child> children) {
            this.name = name;
            this.children = children;
        }

        public String getName() {
            return name;
        }

        public List<Child> getChildren() {
            return children;
        }

        @Override
        public String toString() {
            return name + ": " +
                children.stream()
                    .map(Object::toString)
                    .collect(Collectors.joining(", "));
        }
    }
}

Perform several operations on the List<Person>:

  • remove persons who have fewer than two children;
  • sort persons by the age of their youngest child;
  • obtain a common List<Child>;
  • sort children by name and age.

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in