java - 如何使用 Java 中的 Streams 添加对象的属性?
问题描述
我正在尝试了解有关流收集器的更多信息。我有一个名为 people 的人的列表。我按名称分组。我想总结我感兴趣的那个特定人的所有属性,并返回一个包含所有属性总和的新对象。
例如,汤姆的薪水为 36000,年龄为 36 岁。
我可以通过迭代每个属性来单独总结这些项目。
如何在一次通过中总结各个属性?
public class Hello {
private static Integer collect2;
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
// Person class with Name, salary, age.
Person person = new Person("Tom",12000,12);
people.add(person);
people.add(person);
people.add(person);
Map<String, List<Person>> collect = people.stream().collect(
Collectors.groupingBy(Person::getName));
Integer age = collect.get("Tom").stream()
.map(Person::getAge).collect(Collectors.summingInt(Integer::intValue));
Integer salary = collect.get("Tom").stream()
.map(Person::getSalary).collect(Collectors.summingInt(Integer::intValue));
System.out.println(age + "\n" + salary);
}
}
解决方案
请尝试以下代码:
people.stream().collect(
groupingBy(
p -> p.name,
collectingAndThen(reducing((a, b) -> new Person(a.name, a.salary + b.salary, a.age + b.age)), Optional::get)
)
).forEach((id, p) -> System.out.println(p));
或者
people.stream().collect(
Collectors.toMap(p -> p.name, Function.identity(),
(a, b) -> new Person(a.name, a.salary + b.salary, a.age + b.age))
).forEach((id, p) -> System.out.println(p));
推荐阅读
- html - 将外部 CSS 样式表与 Shopify 产品页面链接
- python - 如何在python中将输出转换为dict?
- laravel - Laravel webpack.mix:当scss翻译成css时出现字体导入字符串中的换行符
- javascript - LightningChartJs点系列在改变角度路线后消失
- reactjs - Shouldn't useContext() only be used for low frequent updates? (mobx-react-lite)
- laravel - Laravel 验证是否多次选择相同的项目
- html - 当容器溢出-y 为自动且容器未溢出时如何看不到背景
- hibernate - 如何在不先进行连接的情况下在多对多连接表中插入记录?
- azure - 与 azcopy sync 相比,使用 Azure 文件同步将本地数据迁移到 Azure 存储有哪些优势?
- c++ - 转换后获取新机器人的航向