I have a method like below:
public void method ()
{
List<String> list1 = someOperation();
List<List2Class> list2;
long failedCount = 0;
for (String element : list1) {
try {
list2 = someclass.method1(element);
list2 = someclass.method2(element);
someclass.saveToDB(list2);
} catch (Exception e) {
failedCount++;
}
}
//some checks on failedCount
}
I want to convert the for loop into parallel stream, can someone tell me what should be the code changes in the above method for the same? PS - method1 and method2 are returning modified version of list2.
The logic here is basically "the result of the last successful operation".
Assuming you don't need the
failedCount
(you don't show it being used), you can do that like this: map successful operations to a presentOptional
, failed operations to an absentOptional
; and just take the last present optional:where
runOperation
is something like:You then need to decide what value
list2
should have if no operations succeed.If you actually do need the
failedCount
, you can break this up a bit:Now
partitioned.get(true)
has all the successful results, whilepartitioned.get(false)
has all the failed results. So: