zoukankan      html  css  js  c++  java
  • 使用函数式接口

    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表达式的类型检查过程
  • 相关阅读:
    在你想要放弃的那一刻,想想为什么当初坚持走到了这里
    将来的你一定会感谢现在奋斗的自己
    学习改变命运,拼搏成就未来
    springmvc的DispatcherServlet源码——doDispatch方法解析
    SpringMVC02 AbstractController And MultiActionController
    SpringMVC简介01
    NIO
    数据库的锁机制
    Spring和MyBatis环境整合
    事务的隔离级别和mysql事务隔离级别修改
  • 原文地址:https://www.cnblogs.com/fly-book/p/12637575.html
Copyright © 2011-2022 走看看