java8之lambda四种基本的函数式接口

Java8-Lambda:内置四大函数式接口

 

https://blog.csdn.net/dengdai123654/article/details/123649657

jdk8中提供了四中最基本的函数式接口供我们使用,减少我们编写额外的接口。

Predicate:泛型单入参返回布尔值出参
Function:泛型单入参返回泛型出参
Supplier:无入参返回泛型出参
Consumer:泛型单入参无出参
这四种是使用最多的函数式接口,都是单参或无参。多入参的如BiFunction等函数式接口可以打开jdk包自行查找。

Predicate:

@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);
}


@Test
public void customPredicate(){
predicate("hello",x-> x.contains("x"));
}

/**
* 入参 --> true/false
* @param str
* @param t
*/
public void predicate(String str, Predicate<String> t){
if(t.test(str)){
System.out.println("haha");
}else {
System.out.println("what's up");
}
}
Function:

@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);
}

@Test
public void customFunction(){
System.out.println(function(10, x -> x * x));
}

/**
* 入参 --> 出参
*/
public int function(int i, Function<Integer,Integer> f){
return f.apply(i);
}
Supplier:

@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
* @return a result
*/
T get();
}

@Test
public void customSupplier(){
System.out.println(supplier(10, () -> new Random().nextInt(20)));
}
/**
* 空参 --> 出参
* @return
*/
public int supplier(int i, Supplier<Integer> s){
return s.get();
}
Consumer:

@FunctionalInterface
public interface Consumer<T> {

/**
* Performs this operation on the given argument.
* @param t the input argument
*/
void accept(T t);
}

@Test
public void customConsumer(){
consumer(10, (x) -> System.out.println(++x));
}
/**
* 入参 --> 空参
*/
public void consumer(int i, Consumer<Integer> c){
c.accept(i);
}

————————————————
版权声明:本文为CSDN博主「一只渣渣」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/dengdai123654/article/details/123649657

 
posted @ 2023-03-02 10:56  liness0713  阅读(77)  评论(0编辑  收藏  举报