??java8中提供了四個(gè)內(nèi)置的函數(shù)式接口,通過直接使用這四個(gè)接口,或者使用它們的擴(kuò)展接口,可以讓我們很方便的使用lambda表達(dá)式毫别。
1. Consumer<T> 消費(fèi)型接口
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
- 例子
import java.util.function.Consumer;
@Test
public consumerTest() {
// 消費(fèi)型接口 有參數(shù),無返回值
Consumer<String> consumer = t -> {
System.out.println(t);
};
consumer.accept("consumer");
}
輸出:consumer
2. Supplier<T> 提供型接口
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
- 例子
import java.util.function.Supplier;
@Test
public supplierTest() {
// 供給型接口 無參數(shù)典格,有返回值
Supplier<String> supplier = () -> {
return "supplier";
};
System.out.println(supplier.get());
}
輸出:supplier
3. Function<T, R> 函數(shù)型接口
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
- 例子
import java.util.function.Function;
@Test
public functionTest() {
// 函數(shù)型接口 有參數(shù)岛宦,有返回值
Function<Integer, Integer> function = s -> {
return s*2;
};
System.out.println(function.apply(1));
}
輸出:2
4. Predicat<T> 斷言型接口
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
- 例子
import java.util.function.Predicate;
@Test
public predicateTest() {
//斷定型接口 有參數(shù),返回值為boolean
Predicate<String> predicate = s ->{
if (s == "predicate") {
return true;
}
return false;
};
System.out.println(predicate.test("predicate"));
}
輸出:ture