Search code examples
javalistdictionarystream

from list to map with Stream


Complete (without modifying Group and Person) the Main class in the two points marked in Bold

public class Group {
public List<Person> people;
public Group(Person ... people)
{
    this.people=Arrays.asList(people);
}
}

public class Person {
public String name;
public String surname;
public int age;

public Person(String name, String surname, int age) {
    this.name=name;
    this.surname=surname;
    this.age=age;
}
}


public class Main {
public static void main(String[] args)
{
    Person p1=new Person("Mario","Bros",36);
    Person p2=new Person("Luigi","Bros",36);
    Person p3=new Person("Peach","Miss",36);
    Person p4=new Person("Toad","Mister",33);
    Person p5=new Person("Toadette","Miss",34);
    Person p6=new Person("Rosalinda","Miss",50);
    
    Group g1=new Group(p6,p4,p1);
    Group g2=new Group(p5,p3,p1,p4);
    Group g3=new Group(p1,p2,p3,p6,p5);
    List<Group> groups=List.of(g1,g3,g2,g1);
    

//starting from groups obtain the map "map1" with keys the distinct groups and values ​​the number of people.

The only instruction with the use of streams

//starting from groups obtain "map2" with keys the distinct groups and values ​​the number of people aged> 35.

The only instruction with the use of streams


Solution

  • Map<Group, Integer> groupSizes = groups.stream()
                                        .distinct() //pick only distinct groups
                                        .collect(Collectors.toMap(
                                            k -> k, //the key of map is the group object
                                            v -> v.people.size() //the value is the size of people from group
                                        ));
    
    groupSizes.forEach((k,v) -> System.out.println(k + " - " + v));
    
    System.out.println("-----");
    
    Map<Group, Integer> groupCountOver35 = groups.stream()
                                                .distinct() //pick only distinct groups
                                                .collect(Collectors.toMap(
                                                    k -> k, //the key is the group
                                                    v -> v.people.stream() //value is the count of people over 35
                                                                .filter(e -> e.age > 35) //pick only people over 35
                                                                .mapToInt(e -> 1)
                                                                .sum() //count them
                                                ));
    
    groupCountOver35.forEach((k, v) -> System.out.println(k + " - " + v));