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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With