Given million number in a list. How to mutiply each element by a constant with minimum time complexity

With Streams, this is simple, here's an example with 100 numbers:
    Integer MUTIPLY_ELEMENT = 2;
    List<Integer> resultNumbers = IntStream.range(0,100)
            .parallel()
            .map(i->i*MUTIPLY_ELEMENT)
            .boxed()
            .collect(Collectors.toList());
if you do care about ordering, but still want to gain the benefit of parallel processing, you can take advantage of the fact that your operation (multiplying by 2) is simple enough that the resulting numbers will still be in the same relative "natural" order and just call sorted() on the stream after the map()call. However, the sorting operation could very well take just as long as if you just did it single threaded.
Also, understand that this is by NO MEANS a "real world" scenario, you will almost never come across an actual problem like this. Hopefully you're just trying to get your head around parallelism in general, because you'd never actually want to do this type of optimization until you have tried a single-threaded model and it proves insufficient.

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance