subrat-kumar-padhi / DockerDemo

0 stars 0 forks source link

completable future example #1

Open rkpatra201 opened 2 years ago

rkpatra201 commented 2 years ago

@subrat-kumar-padhi

private static String findLength(String item)
    {
        return "item name: "+item+": [char count in item] : "+item.length();
    }
    public static void main(String[] args) {

        List<CompletableFuture<String>> futures = new ArrayList<>();

        String[] items = {"laptop api","mobile api","mouse api","processor api","memory api"};
        Arrays.stream(items).forEach(e->{
            futures.add(CompletableFuture.supplyAsync(()->
                    findLength(e)
            ));
        });

        futures.stream().forEach(e->{
            try {
                System.out.println(e.get());
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } catch (ExecutionException ex) {
                ex.printStackTrace();
            }
        });

    }
rkpatra201 commented 2 years ago
 List<String> response = futures.stream().map(e-> {
            try {
                return e.get();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } catch (ExecutionException ex) {
                ex.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());