Reputation: 1391
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));
Upvotes: 2
Views: 782
Reputation: 40044
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).
Upvotes: 5