简体   繁体   中英

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. 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). 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?

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.

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