Functional Interface
CS2030S
1
package cs2030s.fp;
/**
* Represent a conditional statement that returns either true of false.
* CS2030S
* AY23/24 Semester 2
*
* @param <T> The type of the variable to be tested with this conditional statement.
*/
@FunctionalInterface
public interface BooleanCondition<T> {
/**
* The functional method to test if the condition is true/false on the given value t.
*
* @param t The variable to test
* @return The return value of the test.
*/
boolean test(T t);
}BooleanCondition<Integer> isPositive = x -> x > 0;2
package cs2030s.fp;
/**
* Represent a function that produce a value.
* CS2030S
* AY23/24 Semester 2
*
* @param <T> The type of the value produced.
*/
@FunctionalInterface
public interface Producer<T> {
/**
* The functional method to produce a value.
*
* @return The value produced.
*/
T produce();
}Producer<Double> randomValue = () -> Math.random();3
package cs2030s.fp;
/**
* Represent a function that consumes a value.
* CS2030S
* AY23/24 Semester 2
*
* @param <T> The type of the value consumed.
*/
@FunctionalInterface
public interface Consumer<T> {
/**
* The functional method to consume a value.
*
* @param t The value consumed.
*/
void consume(T t);
}Consumer<String> printUpperCase = s -> System.out.println(s.toUpperCase());4
package cs2030s.fp;
/**
* Represent a function that transforms one value into another, possible of different types.
* CS2030S
* AY23/24 Semester 2
*
* @param <U> The type of the input value
* @param <T> The type of the result value
*/
@FunctionalInterface
public interface Transformer<U, T> {
/**
* The function method to transform the value u.
*
* @param u The input value
* @return The value after applying the given transformation on u.
*/
T transform(U u);
}Transfomer<String, Integer> stringLength = s -> s.length();5
package cs2030s.fp;
/**
* Represent a function that combines two values into one. The two inputs
* and the result can be of different types.
* CS2030S
* AY23/24 Semester 2
*
* @param <S> The type of the first input value
* @param <T> The type of the second input value
* @param <R> The type of the return value
*/
@FunctionalInterface
public interface Combiner<S, T, R> {
/**
* The function method to combines two values into one.
*
* @param s The first input value
* @param t The second input value
* @return The value after combining s and t.
*/
R combine(S s, T t);
}Combiner<Integer, Integer, Integer> multiply = (a, b) -> a * b;6
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface Runnable is used to create a thread,
* starting the thread causes the object's run method to be called in that
* separately executing thread.
*/
void run();
}Runnable task = () -> {
System.out.println("Running in thread: " + Thread.currentThread().getName());
};Java
CS2030S
java.util.function
Last updated