四大類函數式接口


供給型接口

Supplier<T>		返回T類型對象
	T get();
Supplier<Apple> supplier = () -> new Apple();
// Supplier<Apple> supplier = Apple::new;
supplier.get();

消費型接口

Consumer<T>		接收一個 T 類型
	void accept(T t);
List<String> languages = Arrays.asList("java","scala","python");
Consumer<String> consumer = System.out::println;
languages.stream().forEach(consumer);

函數型接口

Function<T, R>	由T類型對象轉成R類型對象
	R apply(T t);
List<String> languages = Arrays.asList("java","scala","python");
Function<String, Integer> ti = String::length;
languages.stream()
    .map(ti)
    .forEach(System.out::println);

斷言型接口

Predicate<T>	條件判斷
	boolean test(T t);
List<String> languages = Arrays.asList("java","scala","python");
Predicate<String> p = (str) -> str.length() > 4;
languages.stream()
    .filter(p)
    .forEach(System.out::println);

一個簡單的使用多個函數式接口的例子:

List<String> languages = Arrays.asList("java","scala","python");
Function<String, Integer> ti = String::length;
BiConsumer<Integer, String> bi = (a, b) -> System.out.println(b + a);
IntPredicate ip = x -> x > 4;
IntPredicate ip1 = x -> x < 100;
IntUnaryOperator io = x -> x * x;
languages.stream()
    .map(ti)
    .map(io::applyAsInt)
    .filter(x->ip.and(ip1).test(x))
    .forEach(x -> bi.accept(x, "prefix_"));

部分函數式接口中有 default 方法, 可以進行組合使用!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM