函數(shù)式接口

什么是函數(shù)式接口

  • 只包含一個(gè)抽象方法的接口,稱(chēng)為函數(shù)式接口。
  • 你可以通過(guò) Lambda 表達(dá)式來(lái)創(chuàng)建該接口的對(duì)象。(若 Lambda 表達(dá)式拋出一個(gè)受檢異常,那么該異常需要在目標(biāo)接口的抽象方法上進(jìn)行聲明)。
  • 我們可以在任意函數(shù)式接口上使用 @FunctionalInterface注解, 這樣做可以檢查它是否是一個(gè)函數(shù)式接口,同時(shí) javadoc 也會(huì)包 含一條聲明,說(shuō)明這個(gè)接口是一個(gè)函數(shù)式接口。

自定義函數(shù)式接口

image.png
代碼
package com.www.java8.inter;

/**
 * 函數(shù)式接口
 * <p>
 *
 * @author Www
 * <p>
 * 郵箱: 483223455@qq.com
 * <p>
 * 創(chuàng)建時(shí)間: 2022/8/11  18:27  星期四
 * <p>
 */
@FunctionalInterface
public interface MyFun<T> {
    /**
     * 獲取傳入的參數(shù)
     *
     * @param t
     * @return
     */
    public Integer getValue(Integer t);
}

作為參數(shù)傳遞Lambda 表達(dá)式
image.png

作為參數(shù)傳遞 Lambda 表達(dá)式:為了將 Lambda 表達(dá)式作為參數(shù)傳遞,接 收Lambda 表達(dá)式的參數(shù)類(lèi)型必須是與該 Lambda 表達(dá)式兼容的函數(shù)式接口 的類(lèi)型。

Java 內(nèi)置四大核心函數(shù)式接口

image.png

其他接口

image.png

代碼演示

package com.www.java8.test;

import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8  內(nèi)置的四大核心函數(shù)式接口
 * <p>
 * Consumer<T> :消費(fèi)型接口
 * void accept(T t);
 * <p>
 * Supplier<T> :供給型接口
 * T get();
 * <p>
 * Function<T, R> :函數(shù)型接口
 * R apply(T t);
 * <p>
 * Predicate<T> : 斷言型接口
 * <p>
 * boolean test(T t);
 *
 * @author Www
 * <p>
 * 郵箱: 483223455@qq.com
 * <p>
 * 創(chuàng)建時(shí)間: 2022/8/11  19:39  星期四
 * <p>
 */
public class Lambda2Test {
    
    /**
     * Consumer<T> 消費(fèi)型接口 , 有去無(wú)回
     */
    @Test
    public void testConsumer() {
        happy(46919, m -> System.out.println("享受生活消費(fèi) " + m + "元"));
    }
    
    /**
     * Supplier<T> 供給型 接口
     */
    @Test
    public void testSupplier() {
        List<Integer> numbers = getNumbers(10, () -> (int) (Math.random() * 100));
        numbers.forEach(System.out::println);
        
    }
    
    /**
     * Function<T> 函數(shù)型接口
     */
    @Test
    public void testFunction() {
        String wfsdgfasdf = strHandle("\t\t\t\t\twfsdgfasdf             ", String::trim);
        System.out.println(wfsdgfasdf);
        String str = strHandle("\t\t\t\t\twfsdgfasdf 我愛(ài)中國(guó)sdf", s -> s.substring(s.length() - 7, s.length() - 3));
        System.out.println(str);
    }
    
    
    /**
     * Predicate<T> 斷言型接口
     */
    @Test
    public void testPredicate() {
        List<String> list = Arrays.asList("wefasf", "fasdf", "wsdf", "sdf", "sd", "fs");
        List<String> list1 = filterStr(list, s -> s.length() < 3);
        
        list1.forEach(System.out::println);
    }
    
    public List<String> filterStr(List<String> list, Predicate<String> predicate) {
        List<String> strings = new ArrayList<>();
        for (String string : list) {
            if (predicate.test(string)) {
                strings.add(string);
            }
        }
        return strings;
    }
    
    /**
     * 處理字符串
     *
     * @param str
     * @param fun
     * @return
     */
    public String strHandle(String str, Function<String, String> fun) {
        return fun.apply(str);
    }
    
    /**
     * 產(chǎn)生指定個(gè)數(shù)的整數(shù), 變更放入到集合中
     *
     * @param num
     * @param sup
     * @return
     */
    public List<Integer> getNumbers(int num, Supplier<Integer> sup) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(sup.get());
        }
        return list;
    }
    
    
    /**
     * 消費(fèi)
     *
     * @param money
     * @param consumer
     */
    public void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }
}

package com.www.java8.test;

import com.www.java8.entity.Employee;
import com.www.java8.inter.MyFunction;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.List;

/**
 * 練習(xí)
 * <p>
 *
 * @author Www
 * <p>
 * 郵箱: 483223455@qq.com
 * <p>
 * 創(chuàng)建時(shí)間: 2022/8/11  18:42  星期四
 * <p>
 */
public class LambdaDemo {
    List<Employee> employees = Arrays.asList(
            new Employee("w", 21, 9999.99),
            new Employee("ww", 31, 6666.66),
            new Employee("nw", 31, 6666.66),
            new Employee("lw", 31, 6666.66),
            new Employee("www", 41, 777.66),
            new Employee("l", 1, 5555.555));
    
    /**
     * 先根據(jù) 年齡排序, 年齡一樣時(shí) ,根據(jù) 姓名進(jìn)行排序
     */
    @Test
    public void test1() {
        employees.sort((e1, e2) -> {
            if (e1.getAge().equals(e2.getAge())) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return Integer.compare(e2.getAge(), e1.getAge());
            }
        });
        for (Employee emp : employees) {
            System.out.println(emp);
        }
    }
    
    /**
     * 處理
     */
    @Test
    public void test2() {
        System.out.println("去除空格:");
        String s = strHandler("\t\t\t 我愛(ài)中國(guó)", String::trim);
        System.out.println(s);
        
        System.out.println("將字母轉(zhuǎn)換成 大寫(xiě):");
        String sdfsdf = strHandler("sdfsdf", String::toUpperCase);
        System.out.println(sdfsdf);
        System.out.println("截取字符串:");
        System.out.println(strHandler("wsdfgasdf我愛(ài)中國(guó)", str -> str.substring(str.length() - 4)));
    
    }
    
    /**
     * 處理字符串
     *
     * @param str
     * @param fun
     * @return
     */
    public String strHandler(String str, MyFunction fun) {
        return fun.getValue(str);
    }
    
}

MyFunction

package com.www.java8.inter;

/**
 * <p>
 *
 * @author Www
 * <p>
 * 郵箱: 483223455@qq.com
 * <p>
 * 創(chuàng)建時(shí)間: 2022/8/11  18:50  星期四
 * <p>
 */
@FunctionalInterface
public interface MyFunction {
    /**
     * 將 str 返回
     *
     * @param str
     * @return
     */
    public String getValue(String str);
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容