Need to go through on a complex data structure and modify external variables from the algorithm.
I have tried to do it with stream but as far as I know it is not thread safe, can be race conditions...
Is there a better way than this below copied approach?
List<ObjectA> externalVariable = new ArrayList<>();
List<ObjectA> externalVariable2 = new ArrayList<>();
if (objectA != null) {
externalVariable.add(objectA);
for (ObjectB objectB : objectA) {
if (objectB.getObjectC() != null) {
for (ObjectD objectD : objectB.getObjectC()) {
if (objectD.getObjectE() != null) {
for (ObjectE objectE : objectD.getObjectE()) {
if (objectE.getObjectF() != null) {
for (ObjectG objectG : objectE.getObjectF()) {
objectG.setSomething("BlaBla");
if (objectG.getOjectH() != null && objectG.getOjectH().getObjectI() != null) {
for (ObjectI objectI : objectG.getOjectH().getObjectI()) {
externalVariable2.add(objectI);
ObjectJ objectJ = getRelevantOjectJ(objectA.getId(), objectI.getId());
objectI.setObjectJ(objectJ);
}
}
}
}
}
}
}
}
}
}
forloop, as long as the stream is sequential.for (ObjectB objectB : objectA)objectAin your case), it should never benull.ObjectA impelements Iterable<ObjectB>(which it must if the code works), this makes perfect sense (syntacticall, at least)