I need your help in JAVA (with some sample code if possible) regarding to the following scenario:
I have a list with a classes object and want to check if one object property has duplicates then
keep one of them and add others amounts with the kept one’s amount. For example:
I have this class:
class Salary {
String names;
Double amount;
}
and the list say salary_list contains the following elements in it(for example):
[jony,john 300.96]
[fuse,norvi,newby 1000.55]
[john,jony 22.6]
[richard,ravi,navin 55.6]
[fuse,norvi,newby 200.6]
... ... ...
So what is my expected output is the same input list with the following revised result:
[jony,john 323.56]
[fuse,norvi,newby 1201.15]
[richard,ravi,navin 55.6]
N.B: order in names is not important so not the order of the elements after the duplicate elimination.
I am not good at english as well as in Java. So forgive me if any mistakes there.
Thanks in advance.
Enhance your
Salaryclass as follows:This assumes that
Salaryis immutable (that is, after it’s created the values ofnamesandamountwon’t change. You could then use this with a hash map to add up all the amounts having the same names.At this point the
mapcontains all uniqueSalaryobjects with the total amount for each.