2

I am learning lambda expressions in java. I have the code that uses 'for' loops something like below:

for (RoutingCode routingCode: referencesDao.getRoutingCodes()) {
  ReferencesUtil.routingCodeToXml(references.addElement("referenceType"), routingCode);

  for (AutoCreateIssue ac: referencesDao.getAutoCreateIssues(routingCode.getId())) {
    ReferencesUtil.autoCreateIssueToXml(references.addElement("referenceType"), ac);
  }
}

I want to write a lambda expression for the above. I am able to write the lambda expression if there is only one for loop, but not able to do it when there are nested for loops. Any help is appreciated.

This is what I tried with one loop:

referencesDao.getRoutingCodes().stream().forEach(routingCode -> ReferencesUtil.routingCodeToXml(references.addElement("referenceType"), routingCode));
1
  • @GhostCat Thanks for the response. I am just struggling in passing the routingCode.getId() from the first loop to the second one. Commented May 25, 2021 at 12:06

1 Answer 1

5

Since referencesDao.getRoutingCodes() seems to return a list, you should be able to use forEach directly without streaming. It appears that this is what you're trying to accomplish.

referencesDao.getRoutingCodes()
    .forEach(routingCode -> {
        references.addElement("referenceType", routingCode);
        referencesDao
            .getAutCreatedIssues(routingCode.getId())
            .forEach(ac -> ReferenceUtil
                            .autoCreateIssueToXml(
                                references.addElement(
                                            "referenceType",
                                            ac
                                )
                            )
            );
    });

This is to just provide an idea. It may require some adjustment as I could easily have misinterpreted some of the fields and methods.

For example:

for (AutoCreateIssue ac: referencesDao.getAutoCreateIssues(routingCode.getId()))

If getAutoCreateIssues returns a collection then the built-in method forEach could be used. But if returns an array and using the implicit iterator, then the array would need to be streamed. My example assumed it was a collection (probably a List implementation).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.