I have a list of objects. Each object has few integer fields (id and some values: value1, value2, value3, value4).
id property is unique. There's only one object having a particular id in the list.
Each time I create a new object which has the same id as an existing object, I want to add each value property of the old object to the corresponding value of the new-one and then delete the old-one from the list.
I've tried to add objects to a Set but even though ids are the same, their values are different, so it didn't work.
My current code:
while (true) {
String input = scanner.nextLine();
int id;
int value1;
int value2;
int value3;
int value4;
List<SomeObject> list = new ArrayList<>();
SomeObject record = new SomeObject(id, value1, value2, value3, value4);
list.add(record);
for (SomeObject s : list) {
if (s.getId() == id) {
s.update1(value1);
s.update2(value2);
s.update3(value3);
s.update4(value4);
break;
}
}
list.removeIf(n -> n.getId() == id);
}
SomeObject class:
public class SomeObject {
private int id;
private int value1;
private int value2;
private int value3;
private int value4;
// getters, constructor
public int update1(int x) {
return this.value1 = value1 + x;
}
public int update2(int x) {
return this.value2 = value2 + x;
}
public int update3(int x) {
return this.value3 = value3 + x;
}
public int update4(int x) {
return this.value4 = value4 + x;
}
}
Input example:
id=1243245 1 1 1 1 // old object
id=1243245 2 2 2 2 // new object
Current output:
id=1243245 2 2 2 2 // <- values of the new object
Desired output:
id=1243245 3 3 3 3 // <- combined