Here is a solution without streams(may be easier to understand):
Iterator<UserDetail> it=userDetails.iterator();
Map<String,UserDetail> found=new HashMap<>();
while(it.hasNext()){
UserDetail next=it.next();
if(found.containsKey(next.getUserName())){
found.get(next.getUserName()).setUserSalery(found.get(next.getUserName()).getUserSalery()+next.getUserSalery();
it.remove();
}
else{
found.put(next.getUserName(),next);
}
}
This iterates through all elements.
If it has already found a matching element, it adds its own salery to it and removes itself out of the list.
If not, it marks itself to be found if other elemts are found with the same name later.
This assumes that UserDetail
has standard getter/setter methods for userName
and userSalery
.
Note that a for-each loop cannot be used because you cannot modify the content of the List in there (it would throw a ConcurrentModificationException
).
From the comments(from @Holger:
You can use a single UserDetail previous = found.putIfAbsent(next.getName());
, followed by if(previous != null) { previous.setSalery(previous.getSalery()+next.getSalery()); it.remove(); }
instead of looking up the map three times in a row.
That code would be:
Iterator<UserDetail> it=userDetails.iterator();
Map<String,UserDetail> found=new HashMap<>();
while(it.hasNext()){
UserDetail next=it.next();
UserDetail previous = found.putIfAbsent(next.getUserName());
if(previous != null) {
previous.setUserSalery(previous.getUserSalery()+next.getUserSalery());
it.remove();
}
}
This essentially does the same thing.
It adds the current element to the List if it does not exist and if not, it just adds up the salery.