I have a method which receives an object as parameter that contains a list (firstList) and sublist (secondList) of elements, in which I need to add a new element to the firstList with the resulting value of the subtraction of another two elements contained in the secondList that may be identified by one Enum property value that they have.
Here's an example of the code I have right now:
private void calculateAndAddResultingObject(final MainObject mainObject) {
List<AnObject> firstList = mainObject.getList();
for (AnObject anObject : firstList) {
List<AnotherObject> secondList = anObject.getSublist();
BigDecimal firstOperand = secondList.stream()
.filter(anotherObject -> Enum.VALUE1.equals(anotherObject.getCode())).findAny()
.orElse(new AnotherObject(Enum.VALUE1, BigDecimal.ZERO, mainObject.getProperty()))
.getValue();
BigDecimal secondOperand = secondList.stream()
.filter(anotherObject -> Enum.VALUE2.equals(anotherObject.getCode())).findAny()
.orElse(new AnotherObject(Enum.VALUE2, BigDecimal.ZERO,
mainObject.getProperty())).getValue();
BigDecimal resultingValue = BigDecimal.ZERO;
if (firstOperand.compareTo(secondOperand) > 0) {
resultingValue = firstOperand.subtract(secondOperand);
}
secondList
.add(new AnotherObject(Enum.VALUE2, resultingValue, mainObject.getProperty()));
}
}
How may I reduce the number of iterations to improve performance? Is it possible to do this in a single operation?
Thanks!