How do I add up and remove repeated objects from ArrayList?

Ramana :

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 ??

Eugene :
 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23108&siteId=1