Java – How to join a list of objects with the same key properties

How to join a list of objects with the same key properties… here is a solution to the problem.

How to join a list of objects with the same key properties

If the specific key properties of the object match, I’m trying to connect a custom object

I’m getting data in the following format.

List is like this.

 Data[
{batchNo: "1212", location: "12bbn", qty: "123", rawMaterialId: "6743"},
{batchNo: "1213", location: "12nmn", qty: "300", rawMaterialId: "6743"},
{batchNo: "1241", location: "vbv2", qty: "123", rawMaterialId: "9179"},
{batchNo: "1251", location: "fdsfds", qty: "244", rawMaterialId: "9179"},
{batchNo: "1233", location: "cvcvbc", qty: "200", rawMaterialId: "9169"},
{batchNo: "1266", location: "bnbn", qty: "600", rawMaterialId: "9935"}
]

I’m trying to connect them based on a specific key property (i.e. (rawMaterialId).

For example, if rawMaterialId=6743 of index[0] matches index[1], both require a connection.

Expected List

    Data[
      {batchNo: "1212 , 1213", location: "12bbn , 12nmn", qty: "123 , 300", rawMaterialId: "6743"},
{batchNo: "1241,1251", location: "vbv2 , fdsfds", qty: "123,244",rawMaterialId: "9179"},
{batchNo: "1233", location: "cvcvbc", qty: "200", rawMaterialId:"9169"},
{batchNo: "1266", location: "bnbn", qty: "600", rawMaterialId: "9935"}
   ]

I’ve tried using a For loop but don’t get the expected output

Code which I tried

       for(int i=0; i<data.length; i++)
        {
         for(int j=0; i<data.length; i++)
          {
            if(data[i].rawMaterialId == data[j].rawMaterialId )
            {
                data[i].location=data[i].location +","+ data[j].location;
                data[i].batchNo=data[i].batchNo +"," + data[j].batchNo;
                data[i].quantity=data[i].quantity +"," + data[j].quantity;
            }
        } 
}

Please help me with this and welcome any suggestions and corrections. Thanks in advance.

Solution

If you have array data, you can use the Stream API to transform it. The last line replaces Data with the real type of your project.

data = Arrays.stream(data).        Create stream from your array
    collect(Collectors.toMap(     // Transform it to Map
        d -> d.rawMaterialId,     // It is keys of creating map
        d -> d,                   // This is values of creating map 
        (d1, d2) -> {             // Function for merging values with same keys. 
                                   There happens all neded concatenations.
            d1.location = d1.location + "," + d2.location;
            d1.batchNo = d1.batchNo + "," + d2.batchNo;
            d1.quantity = d1.quantity + "," + d2.quantity;
            return d1;
        }).
    values().toArray(new Data[0]);  Transform map to new array. 
                                    Replace Data to real type of your items.

Related Problems and Solutions