Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use stream api for repeatable actions

I would like to know how to shorten my code with the help of Stream Api. Let's say I have method like this:

public static void createFile( String directoryPath, String fileName )

And I would like to call this method 5 times with the same parameters. For example

        for (int i = 0; i < 5; i++) {
            Utils.createFile(getDirectoryLocation(), "test.txt");
        }

I know I can do something like this:

IntStream.rangeClosed(1, 5).forEach(Utils::someMethod);

But here I am passing one integer value to method. Anyone can give me some hints or answers?

like image 854
Suule Avatar asked Sep 04 '18 08:09

Suule


1 Answers

Streams aren't really helpful here, a simple loop would be better IMO. But if you really wanted to, you could write it via a lambda (ignoring x... ):

IntStream.rangeClosed(1, 5).forEach(x -> Utils.createFile(getDirectoryLocation(), "test.txt"));

I guess one more ugly way could be:

Stream.generate(() -> "test.txt")
            .limit(5)
            .forEach(x -> Utils.createFile(getDirectoryLocation(), x));

Or better:

Collections.nCopies(5, "test.txt")
           .forEach(x -> Utils.createFile(getDirectoryLocation(), x));
like image 154
Eugene Avatar answered Oct 06 '22 15:10

Eugene