Java 8在java.util.function包中引入了几个新的函数式接口:Predicate、Consumer和Function
一、Predicate 断言
java.util.function.Predicate
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Predicate
/**
* 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);
}
使用举例
List
List
System.out.println(nonEmpty); // [hello, java, apple]
二、.Consumer 消费者,没有返回值
java.util.function.Consumer
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Consumer
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
* 接口中默认实现的方法
*/
default Consumer
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
使用举例
public static
for (T t : list) {
c.accept(t);
}
}
List
List
System.out.println(nonEmpty);
forEach(Arrays.asList(1, 2, 3, 4, 5), s -> System.out.println(s));
三、 Supplier 消费者,没有入参
@FunctionalInterface
public interface Supplier
/**
* Gets a result.
*
* @return a result
*/
T get();
}
四、Function 方法
java.util.function.Function
@FunctionalInterface
public interface Function
R apply(T t);
}
使用举例
public static
List
for (T t : list) {
result.add(f.apply(t));
}
return result;
}
List
System.out.println(list); // [5, 4, 3]
测验3.4:函数式接口
对于下列函数描述符(即Lambda表达式的签名),你会使用哪些函数式接口?在表3-2中
可以找到大部分答案。作为进一步练习,请构造一个可以利用这些函数式接口的有效Lambda
表达式:
(1) T->R
(2) (int, int)->int
(3) T->void
(4) ()->T
(5) (T, U)->R
答案如下。
(1) Function
(2) IntBinaryOperator具有唯一一个抽象方法,叫作applyAsInt,它代表的函数描述符是(int, int) -> int。
(3) Consumer
(4) Supplier
(5) BiFunction
| 留言与评论(共有 0 条评论) “” |