【问题标题】:from list to map with Stream使用 Stream 从列表到映射
【发布时间】:2021-07-01 11:11:04
【问题描述】:

粗体标记的两点完成(不修改Group和Person)Main类

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);
    

//从groups开始获取map“map1”,key为不同的groups,value为人数。

唯一使用流的说明

//从groups开始获取“map2”,keys是不同的groups,值是>35岁的人数。

唯一使用流的说明

【问题讨论】:

  • 你能给我们一个输出的例子吗?
  • 对于 map1 我想要 { (g1,3) , (g3,5) , (g2,4) } , 对于 map2 { (g1,2) , (g3,4) , (g2, 3) }

标签: java list dictionary stream


【解决方案1】:
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));

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2019-04-19
    • 2021-09-21
    • 1970-01-01
    • 2018-06-09
    相关资源
    最近更新 更多