I have a method:
invokList(List<Object> list);
This method is inside a jar and I have no access to the source code of it. So for that, I need to execute the invokList in a parallel way, can someone help for this?
The idea is to split the list to many lists and execute invokList in parallel.
I have made this example:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
list.parallelStream()
.map(Collections::singletonList)
.forEach(Test::invokList);
}
public static void invokList(List<Integer> list) {
try {
Thread.sleep(100);
System.out.println("The Thread :" + Thread.currentThread().getName() + " is processing this list" + list);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Best Answer
Guava has methods Lists.partition and Iterables.partition that do something like what you're asking. Say you have a large List and want to process it in chunks of 5, you could do: