Anuja
Anuja

Reputation: 19

How to process 2 lists using parallelStream

I have 2 groups of account number based on CAD and USD currency. Based on these lists I need to call same method by passing request parameters one for CAD and other for USD.

List<List<String>> accountNumberList = Arrays.asList(
      accountNumbersCAD, accountNumbersUSD
);
List<String> response = new ArrayList<>();
accountNumberList.parallelStream().forEach(s -> {
      String response1 = null;
      String response2 = null;
    try {
        response1 = performanceService.retrievePeriodData(reqCAD).toString();
        response2 = performanceService.retrievePeriodData(reqUSD).toString();   
    } catch (ApiException e) {

    }

      response.add(response1);
      response.add(response2);
    });

return (ResponseEntity<String>) response;

Please guide me on how to use parallelStream.

Thanks in advance!

Upvotes: 0

Views: 513

Answers (1)

Michael Dz
Michael Dz

Reputation: 3854

You can't populate a list from a parallel stream using forEach because it will cause unexpected results and the resulting list size might be different each time. Instead use either synchronized list or populate the list using collect method.

List<Double> response = Collections.synchronizedList(new ArrayList<>());

In my opinion mapping inside of the stream doesn't look complicated and there might be no sense of using parallel stream, compare performance of a sequential and parallel stream yourself.

As the second option you can use collect 2 times and it should be more efficient than using a synchronized List.

Function<PerformanceDataRequest, String> mapper = s -> {
    try {
        return performanceService.retrievePeriodData(s).toString();
    } catch (ApiException e) {}
 };

List<String> response = accountNumberList.parallelStream().map(mapper.apply(reqCAD)).collect(Collectors.toList());
response.addAll(accountNumberList.parallelStream().map(mapper.apply(reqUSD)).collect(Collectors.toList()));

I don't know type of what is reqCAD/reqUSD so I put E instead.

Upvotes: 1

Related Questions