0

Can the variable i be removed from the following code (because it is not used)?

IntStream.range(0, 99).parallel().forEach(i -> {
    // do something without variable i
});

EDIT: Does anyone know another representation to execute parallelly 100 times without unnecessary loop counter?

blackeyedcenter
  • 188
  • 1
  • 12
  • 1
    It can't be removed. Even if you replace the lambda expression with a method reference, the method being referenced will require an `int` argument, even if you never use it. – Eran Oct 10 '19 at 06:37
  • 3
    ...which is same as `for(int i=0;i<99;i++)` without using `i` inside the loop – Naman Oct 10 '19 at 06:38
  • @Naman Oh, that's a good point. – blackeyedcenter Oct 10 '19 at 06:56
  • You can always use [Executors.newFixedThreadPool(int n)](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-) – ed22 Oct 10 '19 at 07:00
  • Also - be aware that making stream parallel won't necessarily just run all things in parallel. You still can have a single thread which will run your code sequentially – ByeBye Oct 10 '19 at 12:31

2 Answers2

3

No, you can't because forEach takes IntConsumer as the parameter and the lambda expression you are providing must be compatible with the IntConsumer functional interface. Now look at the IntConsumer interface's accept method it takes one argument :

@FunctionalInterface
public interface IntConsumer {

    void accept(int value);

So, from the above code, you can see that accept(int value) takes an argument.

Amit Bera
  • 7,075
  • 1
  • 19
  • 42
0

Nope, you cannot remove it. The IntConsumer requires an input int parameter.


Assuming you have multiple places in code where you want to do the same thing, you can use the following technique instead.

Create an ExecutorService and define a helper method for repeating a command:

public static ExecutorService service = Executors.newFixedThreadPool(4); // Or any executor service you want

public static void repeat(int times, Runnable command) {
    for (int i = 0; i < n; i++)
        service.execute(command);
    }
};

Then use it as follows:

repeat(100, yourRunnable);
// or
repeat(100, () -> { /* do something here */ });

The repeat method can be implemented using Stream API but it does not guarantee parallel execution of your commands. From the other hand it is blocking and will wait for all the commands to be executed. This might be helpful in some cases:

public static void repeat(int times, Runnable command) {
    IntStream.range(0, times).parallel().forEach(__ -> command.run());
};
ETO
  • 6,970
  • 1
  • 20
  • 37