Java8 内置的四大核心函数式接口

Consumer : 消费型接口

void accept(T t);

Supplier : 供给型接口

T get();

Function : 函数型接口

R apply(T t);

Predicate : 断言型接口

boolean test(T t);

代码示例

package com.imekaku;

import org.junit.Test;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Created by lee on 2017/6/9.
 */
public class TestLambda4 {

    // Consumer<T> 消费型接口
    @Test
    public void test1() {
        happy(55.5, (x) -> System.out.println("花费了这么多钱: " + x));
    }

    private void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

    // Supplier<T> 供给型接口
    @Test
    public void test2() {
        List<Integer> list = getNumList(10, () -> (int)(Math.random() * 100));
        for (Integer i : list) {
            System.out.print(i + " ");
        }
        System.out.println();

        System.out.println("--------------使用迭代器--------------");
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
    }

    private List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            Integer n = supplier.get();
            list.add(n);
        }

        return list;
    }

    // Function<T, R> : 函数型接口
    @Test
    public void test3() {
        String result = strHandler("hello world", (x) -> x.toUpperCase());
        System.out.println(result);

        String result1 = strHandler("      hello world     ", (x) -> x.trim().toUpperCase());
        System.out.println(result1);
    }

    private String strHandler(String str, Function<String, String> function) {
        return function.apply(str);
    }

    // Predicate<T> : 断言型接口
    @Test
    public void test4() {
        List<String> list = Arrays.asList("imekaku", "com", "www", "sina", "baidu");
        List<String> newList = filterStr(list, (x) -> x.length() >= 5);
        Iterator<String> iterator = newList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    private List<String> filterStr(List<String> list, Predicate<String> predicate) {
        List<String> newList = new ArrayList<>();
        for (String s : list) {
            if (predicate.test(s)) {
                newList.add(s);
            }
        }
        return newList;
    }
}

其他内置接口

屏幕快照 2017-06-09 下午7.32.15

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部