0

CompanyData class contains variable

List<Division> Divisions

Division class contains variables.

String Id,String Name,List<SubD> subD

SubD Class contains

String subId,String subName

Below method prints List

List<Info> dataList = daoImpl.getData(requestId);

Ex: [{"Id":01,"Name":XYZ,"subId":"123","subName":"ABC"},{"Id":01,"Name":XYZ,"subId":"456","subName":"DEF"}]

I am iterating the list using foreach loop:

List<Division> divisionsList = new ArrayList<>();

CompanyData companydata = new ComapanyData();

dataList.stream().forEach(e -> {
Division divisions = new Division();
List<SubD> subList = new ArrayList<>();
SubD subd = new SubD();
divisions.setId(e.get_id());
divisions.setName(e.get_name());
subd.setSubId(e.getSub_id());
subd.setSubName(e.getSub_name());
subList.add(subd);
divisions.setSubD(subList);
divisionsList.add(divisions);
});

The above code prints the data in the below format:

      "divisions": [
            {
                "Id": "01",
                "Name": "XYZ",
                "sub": [
                    {
                        "subId": "123",
                        "subName": "ABC"
                    }
                ]
            },
            {
                "Id": "01",
                "Name": "XYZ",
                "sub": [
                    {
                        "subId": "456",
                        "subName": "DEF"
                    }
                ]
            }
        ]

But is there a way to print the data in the below format If the Id is same the it should print it in the same sub List.

    divisions": [
        {
            "Id": "01",
            "Name": "XYZ",
            "sub": [
                {
                    "subId": "123",
                    "subName": "ABC"
                },
                {
                    "subId": "456",
                    "subName": "DEF"
                }
            ]
        }
    ] 
Abhiram Varma
  • 105
  • 2
  • 9

1 Answers1

0

You are missing hashcode and equals method.

There is no way for you to directly identify whether your list already contains the division.

Add the below in your Division class.

 @Override 
 public boolean equals(Object o) {
    if (this == o)
        return true;
    if (o == null || getClass() != o.getClass())
        return false;

    Division div = (Division) o;

    return id != null ? s.equals(div.id) : div.id == null;
}


@Override 
public int hashCode() {
    return id != null ? id.hashCode() : 0;
}

Refer for more information

And one more thing:

If you are doing List<SubD> subList = new ArrayList<>(); inside loop, it's wrong. You should have getter, setter for list and use that to add item to it.

Something like if sublist of division object is empty, create a list and add item to it. Else add item to it.

To avoid duplicated values, you need to do the same for SubD class also.

Gibbs
  • 21,904
  • 13
  • 74
  • 138