I am trying out few things related to method references using functional interfaces. I wanted to convert a string into the upper case using a bounded receiver and an unbounded receiver.
Although I have understood print1 and print2 methods, I am not sure how the print3 compiles. Because Consumer has the void accept(T t);
which takes a single argument and returns nothing, whereas toUpperCase()
in String class takes no argument but returns
a String. I guess the compiler just checks if the actual argument is a lambda expression/MR and the formal parameter is a Functional Interface. Is it correct?
package com.learn.boundedtypes;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class MRTest
{
public static void main(String[] args)
{
String s = "The quick brown fox jumped over the lazy dog";
print1(s::toUpperCase);
print2(String::toUpperCase, s);
print3(String::toUpperCase, s);
}
public static void print1(Supplier<String> supplier)
{
System.out.println(supplier.get());
}
public static void print2(Function<String, String> function, String s)
{
System.out.println(function.apply(s));
}
public static void print3(Consumer<String> consumer, String s)
{
consumer.accept(s);
System.out.println(s);
}
}
Output:
THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG
THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG
The quick brown fox jumped over the lazy dog