如何使用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对象并将其发送给rest api。我们需要根据List大小。需要使用CompletableFuture

不确定你的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
}
}

最新更新