java8自定义收集器_使用自定义收集器进行Java 8分组?

我有以下课程。

class Person {

String name;

LocalDate birthday;

Sex gender;

String emailAddress;

public int getAge() {

return birthday.until(IsoChronology.INSTANCE.dateNow()).getYears();

}

public String getName() {

return name;

}

}

我希望能够按年龄分组,然后收集人员名称列表,而不是人员对象本身。全部以一个漂亮的lamba表达式表示。

为了简化所有步骤,我链接了当前的解决方案,该解决方案按年龄存储分组的结果,然后对其进行迭代以收集名称。

ArrayList members = new ArrayList<>();

members.add(new OtherPerson("Fred", IsoChronology.INSTANCE.date(1980, 6, 20), OtherPerson.Sex.MALE, "fred@example.com"));

members.add(new OtherPerson("Jane", IsoChronology.INSTANCE.date(1990, 7, 15), OtherPerson.Sex.FEMALE, "jane@example.com"));

members.add(new OtherPerson("Mark", IsoChronology.INSTANCE.date(1990, 7, 15), OtherPerson.Sex.MALE, "mark@example.com"));

members.add(new OtherPerson("George", IsoChronology.INSTANCE.date(1991, 8, 13), OtherPerson.Sex.MALE, "george@example.com"));

members.add(new OtherPerson("Bob", IsoChronology.INSTANCE.date(2000, 9, 12), OtherPerson.Sex.MALE, "bob@example.com"));

Map> collect = members.stream().collect(groupingBy(Person::getAge));

Map> result = new HashMap<>();

collect.keySet().forEach(key -> {

result.put(key, collect.get(key).stream().map(Person::getName).collect(toList()));

});

不理想,为了学习,我想有一个更优雅,更有效的解决方案。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值