Reputation: 650
I have defined a functional interface StringFormatter
as below
public interface StringFormatter{
String format(String s1, String s2);
}
How can I write main class which creates lambda expression for above interface and defines format()
for below 2 results?
s1 + s2
s1 + "-" + s2
Upvotes: 3
Views: 1075
Reputation: 31
StringFormatter formatter = (str1,str2) -> str1 + str2;
StringFormatter formatter1 = (str1,str2) -> str1 + "-" + str2;
String formatedString = formatter.format("Hello", "World");
String formatedString1 = formatter1.format("Hello", "World");
System.out.println("Formated String (Type 1) : "+formatedString);
System.out.println("Formated String (Type 2) : "+formatedString1);
Upvotes: 0
Reputation: 42174
In this case you can easily initialize two variables holding lambda expressions like:
StringFormatter formatter1 = (s1,s2) -> s1 + s2;
StringFormatter formatter2 = (s1,s2) -> s1 + "-" + s2;
Then you can call formatter1.format(s1,s2)
and formatter2.format(s1,s2)
.
Following example:
public class Test {
public interface StringFormatter{
String format(String s1, String s2);
}
public static void main(String[] args) {
final StringFormatter formatter1 = (s1,s2) -> s1 + s2;
final StringFormatter formatter2 = (s1,s2) -> s1 + "-" + s2;
System.out.println(formatter1.format("lorem", "ipsum"));
System.out.println(formatter2.format("lorem", "ipsum"));
}
}
produces output:
loremipsum
lorem-ipsum
Upvotes: 3
Reputation: 56393
We can use a Functional interface as a target type like this:
StringFormatter func = (s1, s2) -> s1 + s2;
in which case you can call it like:
String result = func.format("first","second");
you can also put the logic into a method as such:
static String formatter(StringFormatter func, String s1, String s2){
return func.format(s1, s2);
}
then call it:
String result = formatter((s1, s2) -> s1 + s2, "first", "second");
String anotherResult = formatter((s1, s2) -> s1 +"-"+ s2, "first", "second");
in which case you simply pass the behaviour directly without having to create different inline functions for each scenario.
Upvotes: 3
Reputation: 34450
You might write something like this:
StringFormatter formatter1 = (s1, s2) -> s1 + s2;
StringFormatter formatter2 = (s1, s2) -> s1 + "-" + s2;
Usage:
String result1 = formatter1.format("a", "b"); // ab
String result2 = formatter2.format("a", "b"); // a-b
Upvotes: 2