Java Lab Programs (51) Function

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

java.util.

function
Interface Function<T,R>
Type Parameters:
T - the type of the input to the function
R - the type of the result of the function
This is a functional interface and can therefore be used as the assignment target for
a lambda expression or method reference.

import java.util.function.Function; import java.util.function.Function;


public class Test public class Test
{ {
static String show(String message) public static void main(String args[])
{ {
return "Hello "+message; Function<Integer, Double> half = a -> a / 2.0;
} System.out.println(half.apply(10));
public static void main(String[] args) }
{ }
Function<String, String> fun = Test::show;
System.out.println(fun.apply("R-CAT"));
}
}
import java.util.function.Function; import java.util.function.Function;
public class Test public class Test
{ {
public static void main(String args[]) public static void main(String args[])
{ {
Function<Integer, Double> half = a -> a / 2.0; Function<Integer, Double> half = a -> a / 2.0;
half = half.andThen(a -> 3 * a); half = half.compose(a -> 3 * a);
System.out.println(half.apply(10)); System.out.println(half.apply(5));
} }
} }
import java.util.function.Function; import java.util.function.Function;
public class Test public class Test
{ {
public static void main(String args[]) public static void main(String[] args)
{ {
Function<Integer, Integer> i = Function.identity(); Function < String, Integer > function = (t) -> t.length();
System.out.println(i.apply(10)); System.out.println(function.apply("R-CAT"));
} }
} }
import java.util.function.Function;
public class FunctionDemo
{
public static void main(String[] args)
{
Function < Integer, String > function2 = (number) -> {
if (number % 2 == 0) {
return "Number " + number + " is even";
} else {
return "Number " + number + " is odd";
}
};
System.out.println(function2.apply(11));
}
}
Static Method Reference

interface Sayable
{
void know();
}
public class Test
{
public static void knowledge()
{
System.out.println("Hello, this is Java.");
}
public static void main(String[] args)
{
Sayable sayable = Test::knowledge; sayable.say();
}
}

You might also like