0

Consider the following class

public class samplejson {

private String id;

private List<childmain> orders = new ArrayList<>();

// getters & setters

}

After setting values in the class the output is below :
{
  "main": {
    "id": 1,
    "childmain": [
      {
        "id": 2,
        "childmain": [
          {
            "id": 3,
            "childmain": [

            ]
          }
        ]
      },
      {
        "id": 4,
        "childmain": [
          {
            "id": 5,
            "childmain": [
              {
                "id": 6,
                "childmain": [

                ]
              }
            ]
          }
        ]
      }
    ]
  }
}

Question: I want all the id in the child class in a list. I have tried using streams . I got the id values of immediate child. I want the value of the nested child also.

Code I tried:

List<childmain> somethings= samplejson.getchildmain();
List<String> cleanList = somethings.stream().map(somethings::getid)).collect(Collectors.toList());

Expected output: [2,3,4,5,6]
Actual output: [2,4]
Introvert
  • 1
  • 2
  • Well, to get nested elements, especially if the depth can be variable, you'd need to use either recursion or some stack. Since recursion is easier, have a look at this which should give you a hint on how to do it with streams: https://stackoverflow.com/questions/32656888/recursive-use-of-stream-flatmap – Thomas Oct 19 '22 at 06:51
  • Please also note that your question is of poor quality at the moment, e.g. you're basically just throwing code and data at us with the code not even being compilable. Thus it's hard to help in a more specific way. You might want to read [ask] and consider the following: we are putting time and effort into answering so we value this being appreciated by people putting effort into their questions as well. – Thomas Oct 19 '22 at 06:53
  • 1
    Since the depth is arbitrary, streaming probably is not a good solution. You need to do traversal, either using [breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search) or [depth-first search](https://en.wikipedia.org/wiki/Depth-first_search), whichever you find easier to implement. – Chaosfire Oct 19 '22 at 06:55
  • What is this `samplejson.getchildmain()`? Are you using any library to convert the JSON to a POJO? Show your code. – Abhijit Sarkar Oct 19 '22 at 07:07
  • ``` *Note : I have included the class for reference* public class samplejson { private String id; private List orders = new ArrayList<>(); // getters & setters } – Introvert Oct 19 '22 at 07:26
  • @Introvert Add source code and new information to your question, not as a comment. – Progman Oct 19 '22 at 10:29
  • I would like to see the code that converts the JSON into samplejson Java class – Abhijit Sarkar Oct 20 '22 at 01:28

0 Answers0