有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用java8的completableFuture实现forEach列表循环

List<String> list1 = new ArrayList<String>();
        list1.add("Class1");
        list1.add("Class2");
        List<String> list2 = new ArrayList<String>();
        list2.add("Book1");
        list2.add("Book2");
        
        List<List<String>> combine = new ArrayList<List<String>>();
        List<List<Object>> objList = new ArrayList<List<Object>>();
        combine.add(list1);
        combine.add(list2);
        List<List<Object>> finalResponse = getObjList(combine, objList);
        
    }

    private static List<List<Object>> getObjList(List<List<String>> combine, List<List<Object>> objList) {
        Student std = new Student();
        AtomicInteger counter = new AtomicInteger(0);
        combine.forEach((items)->{
            std.setList(items);
            std.setPageId(counter.incrementAndGet());
            // rest call
            List<Object> response = null; // we are doing rest call here
            objList.add(response);
        });
        return objList;
    }
 

请帮帮我。我们正在准备Student对象并将其发送到RESTAPI。我们需要根据列表执行多次<;列表>;大小需要使用CompletableFuture


共 (1) 个答案

  1. # 1 楼答案

    不确定您的API是什么样子的,但下面是一个示例,让您大致了解如何并行调用API

     @Service
    public class RestService1 {
    
        private final String YOUR_API = "your-api";
    
        @Autowired
        private RestTemplate restTemplate;
    
        Executor executor = Executors.newFixedThreadPool(5);
    
        public void callApi() {
            List<Object> list = List.of(new Object(), new Object(), new Object()); // your list of object. 
            Map<String, String> map = new HashMap<>();
            List<CompletableFuture<Student>> completableFutureList = list.stream().map(object -> {
                return CompletableFuture.supplyAsync(() -> callRestApi(map), executor).thenApply(jsonNode -> callRestApi(jsonNode));
            }).collect(Collectors.toList());
            List<Student> result = completableFutureList.stream()
                    .map(CompletableFuture::join)
                    .collect(Collectors.toList());
        }
    
        private JsonNode callRestApi(final Map<String, String> params) {
            return restTemplate.getForObject(YOUR_API, JsonNode.class, params);
        }
    
        private Student callRestApi(final JsonNode jsonNode) {
            // deserialize it and return your Currency object
            return new Student(); // just for example
        }
    
        // Keep it somewhere in Model package (here just for example)
        private class Student {
            // define your arguments
        }
    }