I am not understanding the reason, for having the compilation error for the below program. Where am I going wrong? I want to print the value of the string as output using method reference.
public class ConsumerDemo{
public static void main(String[] args) {
test("hello", (str)-> str::toUpperCase);
}
public static void test(String str, Consumer<String> consumer) {
consumer.accept(str);
}
}
2 Answers 2
test("hello", String::toUpperCase)
should be the correct syntax.
In order to print the upper case of the input, you can use:
String str = "hello"; // any input value
test(str.toUpperCase(), System.out::println);
answered Oct 19, 2018 at 17:39
Naman
32.8k32 gold badges240 silver badges385 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
zilcuanu
I want to print after converting to uppercase
Ousmane D.
Although this compiles the result of
String::toUpperCase will be ignored.Naman
@Aomine agreed that's why wanted to know what OP was willing to perform with the consumer.
you cannot combine lambda syntax and method reference syntax as such.
You're either looking for:
test("hello", String::toUpperCase);
or:
test("hello", s -> s.toUpperCase());
but this then means the result of String::toUpperCase/s -> s.toUpperCase() is ignored hence, you'll need to perform something more useful. for example:
test("hello", s -> System.out.println(s.toUpperCase()));
answered Oct 19, 2018 at 17:41
Ousmane D.
56.6k8 gold badges101 silver badges134 bronze badges
Comments
lang-java