1. 程式人生 > >java8的正確使用姿勢

java8的正確使用姿勢

one sub get 字符串 AC uml hello ble handler

ackage com.expgiga.Java8;

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內置的四大核心函數式接口
 *
 * 1.Consumer<T>:消費型接口
 * void accept(T t);
 * 2.Supplier<T>:供給型接口
 * T get();
 * 3.Function<T, R>:函數型接口
 * R apply(T t);
 * 4.Predicate<T>:斷言型接口
 * boolean test(T t);
 */
public class TestLambda3 {
    public static void main(String[] args) {
        //Consumer<T>消費型接口
        happy(10000, (m) -> System.out.println("Play Game!: " + m + " yuan"));

        //Supplier<T>
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        for (Integer num : numList) {
            System.out.println(num);
        }

        //Function<T, R>函數型接口
        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);

        //Predicate<T> 斷言型接口
        List<String> list = Arrays.asList("Hello", "you", "me", "Java", "Scala");
        List<String> newlist = filterStr(list, (s) -> s.length() > 3);
        for (String str : newlist) {
            System.out.println(str);
        }
    }

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

    //需求:產生一些整數,並放入集合中
    private static List<Integer> getNumList(int num, Supplier<Integer> sup) {
        List<Integer> list = new ArrayList<>();

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

        return list;
    }

    //需求:用於處理字符串
    private static String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }

    //需求:將滿足條件的字符串放入集合中去
    private static List<String> filterStr(List<String> list, Predicate<String> predicate) {
        List<String> strList = new ArrayList<>();

        for (String str : list) {
            if (predicate.test(str)) {
                strList.add(str);
            }
        }

        return strList;
    }

}

  

java8的正確使用姿勢