java - How do I add up and remove repeated objects from ArrayList?
问题描述
User Detail model:
private String userName;
private int userSalary;
I've a ArrayList of user information
List<UserDetail> userDetails = new ArrayList<>();
UserDetail user1 = new UserDetail("Robert", 100);
UserDetail user2 = new UserDetail("John", 100);
UserDetail user3 = new UserDetail("Robert", 55);
userdetails.add(user1);
userdetails.add(user2);
userdetails.add(user3);
I'm trying to iterate through the array and find out if there are any duplicate entries based on userName
, from the above list I've two records with same user name "Robert"
, in this case I want to add up the userSalary
and remove one record from the List.
Expected new ArrayList:
userName userSalary
Robert 155
John 100
Is this possible ??
解决方案
userDetails.stream()
.collect(Collectors.toMap(
UserDetail::getName,
Function.identity(),
(left, right) -> {
left.setSalary(left.getSalary() + right.getSalary());
return left;
}
))
.values();
This will give you a Collection<UserDetail>
. You can copy that into an ArrayList
if needed, obviously.
推荐阅读
- excel - VBA 从两列中过滤掉数据
- excel - 任务计划程序打开 Excel 文件但继续运行且未完成
- ios - 有没有办法在 Google Maps API 的应用程序加载时打开 InfoWindow?
- c# - ASP.NET CORE REST API(401 未经授权)
- java - HTTP 响应 411:与通信时需要的长度
- javascript - 为什么我的计算器连接而不是执行操作?
- javascript - document.querySelectorAll 在使用 chrome 80 运行的赛普拉斯中不起作用
- c# - 如何在 T-SQL 中将日期时间字段与字符串连接起来
- javascript - 打字稿:如何从两组不同的对象中获取具有相同属性值但不同键的对象
- angular - 合并两个 obervable,但在第一个完成之前不触发第二个