使用函数式接口

Predicate


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @see Predicate
 * @FunctionalInterface
 * public interface Predicate<T> {
 *      boolean test(T t);
 *      //....
 * }
 */
public class Filter {
    public static <T>List<T> filter(List<T> list, Predicate<T> p){
        List<T> res = new ArrayList<>();
        for (T t : list) {
            if (p.test(t)){
                res.add(t);
            }
        }
        return res;
    }
    public static void main(String[] args){
        List<Integer> list = filter(Arrays.asList(1,2,3,4,5),(Integer l)->l%2==0);
        System.out.println(list);
    }
}

Consumer

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @see Consumer
 * @FunctionalInterface
 * public interface Consumer<T> {
 *      void accept(T t);
 *      //....
 * }
 */
public class ForEach {
    public static <T> void forEach(List<T> list,Consumer<T> c){
        for (T t : list) {
            c.accept(t);
        }
    }
    public static void main(String[] args){
        forEach(Arrays.asList(1,2,3,4,5),(Integer i)-> System.out.println(i));
    }
}

Function



import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

/**
 * @see java.util.function.Function
 * @FunctionalInterface
 * public interface Function<T, R> {
 *      R apply(T t);
 *      //...
 * }
 */
public class Map {
    public static <T,R> List<R> map(List<T> list, Function<T,R> f){
        List<R> result = new ArrayList<>();
        for(T s: list){
            result.add(f.apply(s));
        }
        return result;
    }
    public static void main(String[] args){
        List<Integer> l = map(Arrays.asList("lambdas","in","action"),(String s)->s.length());
        System.out.println(l);
    }
}
## Lambda表达式的类型检查过程
posted @ 2020-04-05 15:53  fly_bk  阅读(166)  评论(0编辑  收藏  举报