I am trying to solve the below situation : I have a nested list of custom objects. I have to process the outer list parallel but the inner list objects has to be processed in sequence. I tried list.parallelstream() for the outer list and list.stream() for the inner list but it not working, the inner list values are processed randomly during execution. I thought of using Thread (ExecutorService) but not sure how exactly to start with. Below is my code snippet for the paralalStream:
Code to process the list :
List<List<MyObject>> masterList = getMasterList();
masterList.parallelStream().forEach(innerList -> printSubList(innerList));
Code to populate the list:
private static List<List<MyObject>> getMasterList() {
MyObject myObject1 = new MyObject(1,"ABC-1");
MyObject myObject2 = new MyObject(2,"ABC-2");
MyObject myObject3 = new MyObject(3,"ABC-3");
MyObject myObject4 = new MyObject(1,"XYZ-1");
MyObject myObject5 = new MyObject(2,"XYZ-2");
List<MyObject> innerList1 = new ArrayList<>();
innerList1.add(myObject1);
innerList1.add(myObject2);
innerList1.add(myObject3);
List<MyObject> innerList2 = new ArrayList<>();
innerList2.add(myObject4);
innerList2.add(myObject5);
List<List<MyObject>> masterList = new ArrayList<>();
masterList.add(innerList1);
masterList.add(innerList2);
return masterList;
}
Print the object to verify :
private static Consumer<? super List<MyObject>> printSubList(List<MyObject> innerList) {
innerList.stream();
for(MyObject myObject : innerList) {
System.out.println("System Time = "+ System.currentTimeMillis()+" = "+myObject.getName()+" "+myObject.getId());
}
return null;
}
I am open to use Thread as well, but not sure how in this situation. Any help is really appreciated.
Here is my current output :
System Time = 1603173228270 = ABC-3 3
System Time = 1603173228271 = XYZ-1 1
System Time = 1603173228272 = ABC-1 1
System Time = 1603173228272 = ABC-2 2
System Time = 1603173228272 = XYZ-2 2
But I want it to be :
System Time = 1603173228270 = ABC-1 1
System Time = 1603173228271 = ABC-2 2
System Time = 1603173228272 = ABC-3 3
System Time = 1603173228270 = XYZ-1 1
System Time = 1603173228271 = XYZ-2 2