繁体   English   中英

如何使用 CompletableFuture 将此代码转换为 Java 8 中的异步代码? 我正在使用 Spring 引导

[英]How to convert this code to async in Java 8 using CompletableFuture ? I am using Spring Boot

这是需要异步的代码片段:

List<Course> courses = Lists.newArrayList();
Map<String, Map<String, Student>> result = Maps.newHashMap();

for (Map<String, Object> map : jsonObject) {
   courses.add(getCourse(map, fee));  
   result.put(map.get(GROUP), getInfoMap(map));  
}

PS: for-each循环中的map在两个方法调用中都没有发生突变,它们仅使用信息。

如何使上述代码异步运行? 有两种方法被称为getCourse(map, fee)getInfoMap(map) ,顺序运行它们需要相当长的时间。

    // start parallel operations
    List<Future<Course>> coursesFut = Lists.newArrayList();
    Map<String, Future<Map<String, Student>>> resultsFut = Maps.newHashMap();
    for (Map<String, Object> map : jsonObjec t){
        coursesFut.add(CompletableFuture.supplyAsync(() -> getCourse(map, fee)));
        resultsFut.put(map.get(GROUP), CompletableFuture.supplyAsync(() -> getInfoMap(map)));
    }

    // collect results
    List<Course> courses = Lists.newArrayList();
    Map<String, Map<String, Student>> result = Maps.newHashMap();
    for (Future<Course> cf : coursesFut) {
        courses.add(cf.get());
    }
    for (Map.Entry<String, Future<Map<String, Student>> entry : resultsFut.entrySet()) {
        result.put(entry.getKey(), entry.getValue().get());
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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