I have a slow processor intensive work: doWork(int x)which is called with one integer parameter with different values:
static String doWork(int x) {
...
}
public static void main(String args[]) {
for (int i = 1; i < 100; i++) {
System.println(doWork(i));
}
}
As each call completes, the doWork()result is output to the console. I would like to parallelize this - all calls doWork()are independent and do not mutate any general state. Now I can do it the old way, mess with ExecutorSevice, Future.get()etc., but I would like to do it more cleanly with threads 1 .
So something like this looks like it could almost work:
public static void main(String args[]) {
IntStream.rangeClosed(1, 100).parallel()
.forEach(i -> System.out.println(doWork(i)));
}
... , ( doWork(1) ) ..). forEachOrdered(), : . , forEachOrdered : . , , .
, , idiom map -> collect, doWork() :
public static void main(String[] args) {
System.out.println(IntStream.rangeClosed(1, 100).parallel()
.mapToObj(Main::doWork).collect(Collectors.joining("\n")));
}
! collect() , . , - . , .
, - , . , , " " , , , .
- ? -, Collector, , .
1... , , , fork/join , , , , ?