简体   繁体   English

将两个 ArrayList 并行合并到一个 ArrayList?

[英]Merging two ArrayLists to one ArrayList parallelly?

I need to merge two ArrayLists into one ArrayList but I need it to be done really fast, because the function that's doing this is called bunch of times.我需要将两个 ArrayList 合并到一个 ArrayList 中,但我需要非常快地完成,因为执行此操作的函数被多次调用。 Here is my version of function :这是我的功能版本:

  public ArrayList<Pair<String, Integer>> mergeIdWithGrade(ArrayList<String> id, ArrayList<Integer> grades) {

    ArrayList<Pair<String, Integer>> list = new ArrayList<>();
    for(int i = 0; i< id.size(); i++)
    {
        list.add(new Pair<String,Integer>(id.get(i), grades.get(i)));
    }
    return list;
}

Two ArrayLists that are parameters of the function, they are the same size and element at index i of ArrayList<String> id corresponds to element at index i of the ArrayList<Integer> grades (they are making pair).两个的ArrayLists是该函数的参数,但它们在索引相同的大小和元件iArrayList<String> id对应于元件在索引i的的ArrayList<Integer> grades (他们正在对)。 The complexity of the function is obviously O(n), but I am wondering can this be done using parallelStreams, or generally in parallel using all cores of my CPU?该函数的复杂性显然是 O(n),但我想知道这可以使用 parallelStreams 来完成,还是通常使用我的 CPU 的所有内核并行完成?

Multithread here is a bad idea, because you cannot be sure of the state of the original list.多线程在这里是一个坏主意,因为您无法确定原始列表的状态。 Make sure it is thread safe.确保它是线程安全的。

I would agree with other comments that parallel execution would not probably help.我同意其他评论,即并行执行可能无济于事。 Nevertheless, try this piece of code out and see whether parallel is beneficial for you or not不过,试试这段代码,看看并行是否对你有益

    public List<Pair<String, Integer>> mergeIdWithGrade(List<String> id, List<Integer> grades) {
      return IntStream
            .range(0, Math.min(id.size(), grades.size()))
            .parallel() // try with and without it
            .mapToObj(i -> new Pair(id.get(i), grades.get(i)))
            .collect(Collectors.toList());
    }

Note, here is only mapping is done in different threads.注意,这里只是映射是在不同线程中完成的。 The result will be gathered by the main thread.结果将由主线程收集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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