Java 8 并行流方法参数列表

我有一个方法:


invokList(List<Object> list);

此方法位于 jar 中,我无法访问它的源代码。因此,为此,我需要以并行方式执行invokList,有人可以为此提供帮助吗?


这个想法是将列表拆分为多个列表,并并行执行 invokList。


我做了这个例子:


            import java.util.Arrays;

            import java.util.Collections;

            import java.util.List;


            public class Test {


                public static void main(String[] args) {

                    List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);

                    list.parallelStream()

                            .map(Collections::singletonList)

                            .forEach(Test::invokList);

                }


                public static void invokList(List<Integer> list) {

                    try {

                        Thread.sleep(100);

                        System.out.println("The Thread :" + Thread.currentThread().getName() + " is processing this list" + list);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }


哔哔one
浏览 133回答 2
2回答

小唯快跑啊

Guava有Lists.partition和Iterables.partition的方法,它们可以做一些类似于你要求的事情。假设您有一个大列表,并希望以5个块的形式处理它,您可以执行以下操作:int&nbsp;batchSize&nbsp;=&nbsp;5; Lists.partition(list,&nbsp;batchSize) &nbsp;&nbsp;&nbsp;.parallelStream() &nbsp;&nbsp;&nbsp;.forEach(batch&nbsp;->&nbsp;invokeList(batch));

一只斗牛犬

看起来非常冗长,但您可以尝试以下操作。该方法将使列表块并行运行。runAsync()private void test(List<Object> list, int chunkSize) throws ExecutionException, InterruptedException {&nbsp; &nbsp; AtomicInteger prev = new AtomicInteger(0);&nbsp; &nbsp; List<CompletableFuture> futures = new ArrayList<>();&nbsp; &nbsp; IntStream.range(1, (int) (chunkSize * (Math.ceil(Math.abs(list.size() / (double) chunkSize)))))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(i -> i % chunkSize == 0 || i == list.size())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .forEach(i -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<Object> chunk = list.subList(prev.get(), i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; futures.add(CompletableFuture.runAsync(() -> invokeList(chunk)));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prev.set(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();}private void invokeList(List<Object> list) {&nbsp; &nbsp; System.out.println("Invoked for: " + list);}我为30个整数的列表运行它,块大小为5,如下所示:public static void main(String[] args) throws ExecutionException, InterruptedException {&nbsp; &nbsp; List<Object> list = IntStream.range(0, 30).mapToObj(i1 -> (Object) String.valueOf(i1)).collect(Collectors.toList());&nbsp; &nbsp; int chunkSize = 5;&nbsp; &nbsp; new Test().test(list, chunkSize);}输出:Invoked for: [15, 16, 17, 18, 19]Invoked for: [0, 1, 2, 3, 4]Invoked for: [5, 6, 7, 8, 9]Invoked for: [10, 11, 12, 13, 14]Invoked for: [20, 21, 22, 23, 24]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java