Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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

like image 868
Ramana Avatar asked Mar 03 '20 16:03

Ramana


Video Answer


1 Answers

 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.

like image 127
Eugene Avatar answered Oct 05 '22 05:10

Eugene