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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With