Skip to content
Advertisement

Java aggregate same objects into one

I’m quite new into programming and got a tricky question. I got an object which has multiple parameters:

JavaScript

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:

JavaScript

I am receiving one object of AnotherClass containing multiple entities of SampleClass in a list.

What I want to do is merge all SampleObjects 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:

JavaScript

Desired state:

JavaScript

What I have already done is the following:

JavaScript

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?

Advertisement

Answer

Based on your usage of Collector.joining() I assume that you want to concatenate all non-null values without any delimiters (anyway it can be easily changed).

In order to combine SampleObject instances having the same number property, you can group them into an intermediate Map where the number would serve as Key and a custom accumulation type (having properties valueOne, valueTwo, valueThree) would be a Value (note: if you don’t want to define a new type, you can put the accumulation right into the SampleObject, but I’ll go with a separate class because this approach is more flexible).

Here’s it might look like (for convenience, I’ve implemented Consumer interface):

JavaScript

To create an intermediate Map we can use Collector groupingBy() and as its downstream Collector, in order to leverage the custom accumulation type, we can provide a custom collector, which can instantiated using factory method Collector.of().

Then we need to create a stream over the entries of the intermediate map in order to transform the Value.

Note that sorting applied in only the second stream.

JavaScript
Advertisement