vendredi 20 mars 2015

Translate complex conditional logic inside a loop into streams and lambdas

I'm looking for a clean way to translate complex logical conditions with if and else statements that lead to different actions, to lambdas and streams.


Suppose I have this code:



List<OuterData> result = new LinkedList<>();

for (Outer outer : getOutersFromSomewhere()) {
OuterData outerData = new OuterData();

if (outer.isImportant()) {
doImportantAction(outer, outerData);
} else if (outer.isTrivial()) {
doTrivialAction(outer, outerData);
} else {
doDefaultAction(outer, outerData);
}

for (Inner inner : outer.getInners()) {
if (inner.mustBeIncluded()) {
InnerData innerData = new InnerData();

if (inner.meetsCondition1()) {
doAction1(inner, innerData, outer, outerData);
} else if (inner.meetsCondition2()) {
doAction2(inner, innerData, outer, outerData);
} else {
doDefaultAction(inner, innerData, outer, outerData);
}
outerData.add(innerData);
}
}
result.add(outerData);
}

return result;


This is simplified from real code I have. I know it can be optimized and refactored, i.e. I could move inner for to a private method. I'd like to know how to translate the if, else if and else parts to streams and lambdas.


I know how to translate the skeleton of this example. I'd use List.stream(), Stream.map(), Stream.filter(), Stream.collect() and Stream.peek(). My problem is with conditional branches only. How can I do this translation?


Aucun commentaire:

Enregistrer un commentaire