Java 8 environment.
run tasks using CompletableFuture.allOf() concurrently and then get each result from each thread and then combine all results into one combinedResult and return it.
In the below code, to get the result ( = List<Student>
) it doesn't have to be the code between I. and II.
They say I need to use join() but didn't work
I also got some allOf() from
Java 8 CompletableFuture.allOf(...) with Collection or List
and other links, but nothing works for me.
I think I miss some very easy part. Does someone know how to make it work?
public class Test1 {
public static void main(String[] args) {
Test1 t = new Test1();
Map<Major, List<Student>> allMajorStudentListMap = new HashMap<>();
// fill out some data toallMajorStudentListMap
t.getData(allMajorStudentListMap);
}
List<Student> getData(Map<Major, List<Student>> allMajorStudentListMap) {
List<CompletableFuture<List<Student>>> completableFutures = new ArrayList<>();
// suppose the size of completableFutures is 10
for(Map.Entry<Major, List<Student>> entry: allMajorStudentListMap.entrySet()) {
CompletableFuture<List<Student>> future = CompletableFuture.supplyAsync(() -> getDetailedStudents(entry));
completableFutures.add(future);
}
// want to run 10 jobs concurrently --> get the 10 result and then combine these 10 results into one
// finally want to sent the combined 10 results at one in this method
// I. ======================= I got this code from somewhere ==========================
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]))
.exceptionally(ex -> null)
.join();
Map<Boolean, List<CompletableFuture<List<Student>>>> result =
completableFutures.stream()
.collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally));
result.forEach((k, clist) -> {
System.out.printf("k = " + k);
for(CompletableFuture<List<Student>> student: clist) {
// 3) don't know how to get only List<Student> and then print here
// tried this and that but didn't work
// student.get() has compile error
}
});
// II. =============================================================================================
// want to return combined List<Student>
return ???;
}
List<Student> getDetailedStudents(Map.Entry<Major, List<Student>> entry)
{
List<Student> studentList = new ArrayList<>();
Major major = entry.getKey();
String majorCode = major.getMajorCode();
String majorName = major.getMajorName();
List<Student> studentListList = entry.getValue();
studentList.addAll(getDataFromRemote(majorCode, majorName, studentList)));
return studentList;
}
List<Student> getDataFromRemote(String majorCode, String majorName, List<studentList> studentList) {
// do something and then return list of Student
return detailedStudentList;
}
}