简体   繁体   中英

How to implement forEach loop of list using completableFuture of java8

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;
    }
 

Please help me.We are preparing the Student object and sending it to rest api. We need to do multiple time depending on List<List> size.Need to use CompletableFuture

Not sure about how your API looks like but below is an example that gives you a fair idea of how you can call your API in parallel.

 @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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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