This is my first approach to lambda expressions, function as parameter or in general functional programming...
How I can call B function in this code?
public class Fp_example<T>
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<>(asList("A"));
new Fp_example.b_function(names, /* (1) */);
}
public void b_function(ArrayList<T> l, Function<T,T> func)
{
l.forEach( (t) -> {func.apply(t);});
}
}
I need to write my function in (1), or can I write another function and just call it inside (1)?
First of all, you should instantiate Fp_example<String>
, since you are passing an ArrayList<String>
to b_function
.
Now, it's up to you which function to pass to the method, depending on how you wish to transform the input String
s. Any lambda expression that takes a String
argument and returns a String
will do.
For example, you can pass a lambda expression that reverses the input String
s :
new Fp_example<String> ().b_function(names, s -> new StringBuilder(s).reverse().toString());
or
Function<String,String> a_function = s -> new StringBuilder(s).reverse().toString();
new Fp_example<String> ().b_function(names, a_function);
You might want to display the output of applying the function on the input elements, though :
public void b_function(ArrayList<T> l, Function<T,T> func)
{
l.forEach( (t) -> {System.out.println(func.apply(t));});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.