I'm quite new into programming and got a tricky question. I got an object which has multiple parameters:
public class SampleObject {
private String number;
private String valueOne;
private String valueTwo;
private String valueThree;
// getters, setters, all-args constructor
}
Every object always has non-null number
attribute as well as one of three values-field. So for example, if valueOne
is not null
, the other two value fields valueTwo
and valueThree
would be null
.
So here's my problem:
The SampleObject
is referenced in AnotherClass
which looks so:
public class AnotherClass {
private UUID id;
private List<SampleObject> sampleObjects;
// getters, setters, all-args constructor
}
I am receiving one object of AnotherClass
containing multiple entities of SampleClass
in a list.
What I want to do is merge all SampleObject
s which got the same number into one object and provide a map, where the number is the key and value are the value parameters. For example:
Sample1(number:"1", valueOne="1", valueTwo=null, valueThree=null)
Sample2(number:"1", valueOne=null, valueTwo="2", valueThree=null)
Sample3(number:"1", valueOne=null, valueTwo=null, valueThree="3")
Sample4(number:"2", valueOne="5", valueTwo=null, valueThree=null)
Desired state:
Sample1Merged(number:"1", valueOne="1", valueTwo="2", valueThree="3")
Sample4(number:"2", valueOne="5", valueTwo=null, valueThree=null)
What I have already done is the following:
final Map<String, SampleObject> mapOfMergedSamples = new LinkedHashMap<>();
anotherClass.getSampleObjects().stream()
.sorted(Comparator.comparing(SampleObject::getNumber))
.forEach(s -> mapOfMergedSamples.put(s.getNumber(), new SampleObject(Stream.of(s.getValueOne(), s.getValueTwo())
.filter(Objects::nonNull)
.collect(Collectors.joining()), s.getValueThree()))
);
return mapOfMergedSamples;
The problem with my current try is that every number gets overwritten because they have the same key in the map (the number in the SampleObject
) does someone know how can I archive my desired state?