通过Streams并行执行多个查询

编程入门 行业动态 更新时间:2024-10-24 23:18:38
本文介绍了通过Streams并行执行多个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下方法:

public String getResult() { List<String> serversList = getServerListFromDB(); List<String> appList = getAppListFromDB(); List<String> userList = getUserFromDB(); return getResult(serversList, appList, userList); }

这里我按顺序调用三个方法,然后点击DB并取出我结果,然后我对从DB命中获得的结果进行后处理。我知道如何通过使用 Threads 同时调用这三种方法。但我想使用Java 8 Parallel Stream 来实现这一目标。有人可以指导我如何通过Parallel Streams实现相同的目标吗?

Here I am calling three method sequentially which in turns hits the DB and fetch me results, then I do post processing on the results I got from the DB hits. I know how to call these three methods concurrently via use of Threads. But I would like to use Java 8 Parallel Stream to achieve this. Can someone please guide me how to achieve the same via Parallel Streams?

编辑我只想通过Stream并行调用这些方法。

EDIT I just want to call the methods in parallel via Stream.

private void getInformation() { method1(); method2(); method3(); method4(); method5(); }

推荐答案

您可以使用 CompletableFuture 这样:

public String getResult() { // Create Stream of tasks: Stream<Supplier<List<String>>> tasks = Stream.of( () -> getServerListFromDB(), () -> getAppListFromDB(), () -> getUserFromDB()); List<List<String>> lists = tasks // Supply all the tasks for execution and collect CompletableFutures .map(CompletableFuture::supplyAsync).collect(Collectors.toList()) // Join all the CompletableFutures to gather the results .stream() .map(CompletableFuture::join).collect(Collectors.toList()); // Use the results. They are guaranteed to be ordered in the same way as the tasks return getResult(lists.get(0), lists.get(1), lists.get(2)); }

更多推荐

通过Streams并行执行多个查询

本文发布于:2023-11-03 12:30:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555140.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   Streams

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!