天天看点

Java8新特性之函数式接口学习

函数式接口

只包含一个方法的接口(default方法除外)称为函数式接口。可用@FunctionalInterface注解修饰,可以语法检查。

@FunctionalInterface
public interface InterfaceTest {
	void test();
    
	default void defaultMethod() {}
}
           

四大内置核心函数式接口

  • Lambda表达式需要用到函数式接口,而大部分的Lambda表达式的函数式接口都是很简单的,这些简单的接口如果需要程序员手动再新建的话,实在太麻烦,所以Java8为我们提供了4类内置函数式接口,方便我们调用, 这4类接口已经可以解决我们开发过程中绝大部分的问题 。
  1. 消费型接口(有去无回)
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
    ...
}
           

使用示例:(将字符串作为输入,然后做打印处理,相当于“消费”了)

@Test
public void test1() {
	Consumer<String> consumer = (str) -> System.out.println(str);
	consumer.accept("hello consumer!");
}
           
  1. 供给型接口(凭空捏造)
    @FunctionalInterface
    public interface Supplier<R> {
        R get();
    }
               
    使用示例:(随机生成一个100以内的整数,无入参)
    @Test
    public void test2() {
    	Supplier<Integer>  supplier = () -> (int)(Math.random()*100);
    	Integer num = supplier.get();
    	System.out.println(num);
    }
    
               
  2. 函数型接口(有来有回)
    @FunctionalInterface
    public interface Function<T, R> {
        R apply(T t);
        ...
    }
               
    使用示例:(传入一个字符串,返回一个前后无空格的字符串,”有来有回“)
    @Test
    public void test3() {
    	Function<String, String> function = (str) -> str.trim();		
        String str = function.apply("\t\t\tHello! ");
    	System.out.println(str);
    }
               
  3. 断言型接口(判断对错)
    @FunctionalInterface
    public interface Predicate<T> {
        boolean test(T t);
        ...
    }
               
    使用示例:
    @Test
    public void test4() {
    	List<Integer> list = Arrays.asList(1, 3, 5, 10, 22);
    	//过滤得到所有奇数
    	List<Integer> list1 = filterNum(list, (num) -> num % 2 == 0 ? false : true);
    	list1.forEach(System.out::println);
    		
    	System.out.println("========================");
    		
    	//过滤得到所有大于5的数
    	List<Integer> list2 = filterNum(list, (num) -> num > 5);
    	list2.forEach(System.out::println);
    }
    	
    public List<Integer> filterNum(List<Integer> list, Predicate<Integer> predicate){
    	List<Integer> res = new ArrayList<>();
    	for (Integer num : list) {
    		if (predicate.test(num)) {
    			res.add(num);
    		}
    	}
    	return res;
    }
               

除上述四个函数式接口外,Java8还提供了一些衍生的接口帮助我们处理更多的情况

public interface BiConsumer<T, U> {void accept(T t, U u);} 
public interface BiFunction<T, U, R> {R apply(T t, U u);}
public interface BiPredicate<T, U> {boolean test(T t, U u);}

public interface DoubleConsumer {void accept(double value);}
public interface DoubleSupplier {double getAsDouble();}
public interface DoubleFunction<R> {R apply(double value);}
public interface DoublePredicate {boolean test(double value);...}

...
           
Java8新特性之函数式接口学习

所以我们可以根据不同的场景选择使用不同的接口,当然也可以自定义。