I make myself familiar with Java 8's so called method references.
Two questions:
1) I want to println uppercased values. How can I pass the result of String::toUpperCase to println? For example this block of code doesn't compile:
List<String> food = Arrays.asList("apple", "banana", "mango", "orange", "ice");
food.forEach(System.out.println(String::toUpperCase));
2) Is there something similar to anonymous function parameters (_) like is Scala?
1 Answer 1
What you want to do is to combine a function with a consumer.
You can do it this way:
food.stream().map(String::toUpperCase).forEach(System.out::println);
Alternatively you can use a lambda expression:
food.forEach(x->System.out.println(x.toUpperCase()));
Besides these straight-forward approaches, you can combine functions to create a new function but not a function with a consumer, however, with the following quirky code you can do it:
Function<String,String> f0=String::toUpperCase;
food.forEach(f0.andThen(" "::concat).andThen(System.out::append)::apply);
This get even uglier if you try to inline the first expression for a one-liner...
2 Comments
Stream is the way how to combine arbitrary operations._ is a reserved keyword and might be a placeholder for parameters you don’t want to use in a future Java version, however, that doesn’t apply here as here the parameters are used.
printlnis a void method, so obviously you can't pass its result toforEach.