Kevin Valdez
Kevin Valdez

Reputation: 389

Populate List inside List With Conditionals Java

I'm trying to populate a List<Object> that has as a attribute another List.

Here is The Scenario.

First Object

public class Student {

    private String initials;
    private String id;
    private List<StudentDetail> listStudentDetail;

    //Setters and Getters

}

Second Object

public class StudentDetail {

    private String id;
    private String name;

    //Setters and getters
}

My final java object is as follows.

public class Response {

    private String code;
    private String message;
    private List<Student> listStudent;

    //Setters and getters
}

I get populated a List<Student>and a List<StudentDetail> from another process and what I want to achive is merge both list into my Response class but with theese particular conditions

In order to fill List<StudentDetail>

These is what I want to Achieve.

{
  "code": "0",
  "message": "Succes",
  "listStudent": [
    {
      "initials": "a",
      "id": "104",
      "listStudentDetail": [
        {
          "id": "104",
          "name": "Kevin"
        }
      ]
    },
    {
      "initials": "b",
      "id": "100",
      "listStudentDetail": []
    },
    {
      "initials": "a",
      "id": "105",
      "listStudentDetail": [
        {
          "id": "105",
          "name": "Robert"
        }
      ]
    }
  ]
}

Upvotes: 0

Views: 71

Answers (1)

Vishakha Lall
Vishakha Lall

Reputation: 1314

Here is the code.
I am assuming populatedStudentList and populatedStudentDetail as the given objects that have been populated in some other part of the code like you mentioned.

for (Student s in populatedStudentList){
    if (s.getInitials().compareTo('a') != 0){
        continue;
    }
    String findId = s.getId();
    List<StudentDetail> tempListStudentDetail = new ArrayList<>(); 
    for (StudentDetail d in populatedStudentDetail){
        if (d.getId().compareTo(findId) == 0){
             tempListStudentDetail.append(d);
        }
    }
    s.setListStudentDetail(tempListStudentDetail);
}

This can be achieved in a more memory efficient manner using hashTables but I have tried to reproduce the desired result in the most basic manner.

Upvotes: 1

Related Questions