简体   繁体   中英

Java Parallel processing with return value

List<String> lines = FileUtils.readLines(dataFile,"UTF-8");
lines.parallelStream().forEachOrdered(line->processRecord(line, dataFileName)); 

here process record will return string value how to store to any collection / file

could help me for this. thanks for advance.

Instead of using forEachOrdered you could use map to execute and store the result for each of the inputs. You can then collect these into a new list to store the results.

Example:

        List<String> result = lines.parallelStream()
            .map(line->line.toUpperCase())
            .collect(Collectors.toCollection(ArrayList::new));

[Answer is based on comments]

Assuming, you want to process a list of String and also want to store the response of each processing with input and output, then you can follow the below approach.

 List<String> lines = FileUtils.readLines(dataFile,"UTF-8");
 Map<String, String> result = lines.parallelStream()
       .collect(Collectors.toMap(line -> line, line -> processRecord(line, dataFileName)));

Here, the result (a simple Map<Key, Value> ) will contain both.. the key as each single line, and value as each single response of THAT line returned by processRecord method.

how many threads will execute parallelly this method (from comments)

The method parallelStream() uses threads form DefaultForkJoinPool . And this pool has default size equal to the number of cores on your system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM