0

I have few string values and on basis of that string I need to download few files. What will be most efficient way of doing this in java8.

List<String> keyValues = Arrays.asList("key1", "key2", "key3","key4");
keyValues.stream().forEach(i -> (FileUtils.copyURLToFile(new URL(urlStr + i), new File(filePath + i))) );

forEach is giving error as " is not applicable for the arguments (( i) -> {})"

Any help is highly appreciated. Thanks.

greg-449
  • 109,219
  • 232
  • 102
  • 145
Manvi
  • 1,136
  • 2
  • 18
  • 41
  • 1
    See [this answer](http://stackoverflow.com/a/24147329/2711488). But note that even after fixing the syntax, it won’t work, if `copyURLToFile` declares checked exceptions. – Holger Feb 03 '17 at 08:46
  • try enabling stream().parallel() - looks like the task might be IO intensive so could possibly benefit from it – mwdev Oct 28 '19 at 00:10

2 Answers2

2

Remove the brackets from around your lambda:

keyValues.forEach(i -> FileUtils.copyURLToFile(new URL(urlStr + i), new File(filePath + i)));

My guess is the brackets around the call are confusing the compiler into thinking you have a function instead of a consumer.

Note also that you don't need the call to stream(); you can invoke .forEach() directly from Collections.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 2
    The compiler isn’t confused, an expression in parentheses is always an expression, not a statement. So it can’t be a consumer. The `param -> methodInvocation` form works, because the invocation is both, a statement and an expression. So the compiler is strictly following the rules. The invalidity of bracketed expression is discussed [here](http://stackoverflow.com/a/24147329/2711488), the valid expression statements can be found [here](http://stackoverflow.com/a/41483237/2711488). – Holger Feb 03 '17 at 08:52
  • @Holger "confused" was a turn of phrase. Of course an inanimate determinant program can't be confused. Thanks for the links though. – Bohemian Feb 03 '17 at 08:57
  • Thanks Holger and Bohemian for your explanation but nothing works. I then refer http://blog.agiledeveloper.com/2015/06/lambdas-are-glue-code.html and try to put that one line inside function and called function within lamda.. that worked. – Manvi Feb 03 '17 at 16:15
  • Try wrapping in curly brackets and add a semicolon. Ie `i -> {...;}` – Bohemian Feb 03 '17 at 17:10
0

Its interesting but puting that one line into function and calling that function from lambda works fine..Refer blog : http://blog.agiledeveloper.com/2015/06/lambdas-are-glue-code.html

operatorKeys.forEach(i ->  downloadFile(i));

Obviously surround with proper try/catch bloacks..

Manvi
  • 1,136
  • 2
  • 18
  • 41