Lambda表达式可以用于策略模式,作为一个参数传递,如果我们自己去定义函数式接口,可能会不太方便,Java8内置了四大函数式接口,可以直接使用。
Consumer<T>:消費型接口
void accept(T t)
Supplier<T>:供给型接口
T get();
Function<T,R>:函数型接口
R apply(T t);
Predicate<T>:断言型接口
boolean test(T t);
1.消费型接口
方法接口一个参数消费,无返回值。
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
举例说明:定义一个happy方法,接收double类型数字,以及对它的操作。
public void happy(double money, Consumer<Double> con){
con.accept(money);
}
public void test1(){
happy(10000,(m) -> System.out.println("刚哥喜欢大宝剑,每次消费"+m));
}
2.供给型接口
方法无参数,返回T类型数据
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
举例说明:产生制定个数的整数,并放到集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer> list = new ArrayList<>();
for(int i =0;i<num;i++){
Integer n =sup.get();
list.add(n);
}
return list;
}
public void test2(){
List<Integer> numList = getNumList(10, () -> (int) Math.random() * 10);
for (Integer i:numList) {
System.out.println(i);
}
}
3.函数型接口
对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t);
@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);
}
举例说明:处理字符串
public String strHandler(String str, Function<String,String> fun){
return fun.apply(str);
}
public void test3(){
String newStr = strHandler("/t/t/t lemon a ", (str) -> str.trim());
System.out.println(newStr);
}
4.断言型接口
确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法
boolean test(T 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);
}
举例说明:将满足条件的字符串放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
List<String> strList = new ArrayList<>();
for(String str:list){
if(pre.test(str)){
strList.add(str);
}
}
return strList;
}
public void test4(){
List<String> list = Arrays.asList("Hello","lambda","www","ok");
List<String> strList = filterStr(list, (s) -> s.length() > 3);
for(String str:strList){
System.out.println(str);
}
}