函数式接口
-
函数式接口简介
函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰可以检查是否是函数式接口 -
Java8内置的四大核心函数式接口
- Consumer : 消费型接口
# 消费型接口是void类型,没有返回值
* @param <T> the type of the input to the operation
void accept(T t);
# 例如 Consumer<T> 消费型接口 :
@Test
public void test1(){
// 消费型接口 是void类型 打印输出
happy(10000, (m) -> System.out.println("刚哥喜欢大宝剑,每次消费:" + m + "元"));
}
// 这里使用Consumer接口
public void happy(double money, Consumer<Double> con){
con.accept(money);
}
- Supplier : 供给型接口
# 供给型接口返回泛型类型的对象
* @param <T> the type of results supplied by this supplier
T get();
# 例如 Supplier<T> 供给型接口 : (10, () -> (int)(Math.random() * 100)) 10代表指定生成正式的个数 () -> (int)(Math.random() * 100调用Supplier函数来生成整数
@Test
public void test2(){
List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
for (Integer num : numList) {
System.out.println(num);
}
}
//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
// sup.get()取出生成的整数,放入到list中
Integer n = sup.get();
list.add(n);
}
return list;
}
- Function<T, R> : 函数型接口
# 函数型接口
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
R apply(T t);
# 例如 Function<T, R> 函数型接口:
@Test
public void test3(){
// 调用strHandler方法,把str="\t\t\t 我大硅谷威武" 传入函数型接口,然后调用trim函数来除去空格
String newStr = strHandler("\t\t\t 我大硅谷威武 ", (str) -> str.trim());
System.out.println(newStr);
String subStr = strHandler("我大硅谷威武", (str) -> str.substring(2, 5));
System.out.println(subStr);
}
//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}
- Predicate : 断言型接口
# Predicate<T> 断言型接口:
* @param <T> the type of the input to the predicate
boolean test(T t);
# 例如 Predicate<T> 断言型接口:
@Test
public void test4(){
// 把一个数组转换为集合
List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
// (s) -> s.length() > 3 断言式接口,判断传入的字符串的长度是否大于3,大于3返回true,否则false.
List<String> strList = filterStr(list, (s) -> s.length() > 3);
for (String str : strList) {
System.out.println(str);
}
}
//需求:将满足条件的字符串,放入集合中
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;
}
3. 其他函数式接口