zoukankan      html  css  js  c++  java
  • Lambda表达式

    1.常见单方法接口

    • Comparator
    • Runnable
    • Callable
    普通:
    String [] names={"mushroom","peach","appl","banana"}; Comparator comparator=new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length()-o2.length(); //[appl, peach, banana, mushroom] } };
    Lambda方式:
        
          Comparator<String> comparator=(String name1,String name2)->name1.length()-name2.length(); //[appl, peach, banana, mushroom]

    Comparator<String> comparator=(name1 , name2)->name1.length()-name2.length(); //[appl, peach, banana, mushroom]
     

    2. @FunctionalInterface

    只定义了单方法的接口称之为FunctionalInterface,用注解@FunctionalInterface标记,如Callable接口

     * @see Executor
     * @since 1.5
     * @author Doug Lea
     * @param <V> the result type of method {@code call}
     */
    @FunctionalInterface
    public interface Callable<V> {
        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        V call() throws Exception;
    }

    但 Comparator接口:

    @FunctionalInterface
    public interface Comparator<T> {
    
        int compare(T o1, T o2);
    
        boolean equals(Object obj);
    
        default Comparator<T> reversed() {
            return Collections.reverseOrder(this);
        }
    
        default Comparator<T> thenComparing(Comparator<? super T> other) {
            ...
        }
        
    }

    虽然Comparator接口有很多方法,但只有一个抽象方法int compare(T o1, T o2),其他的方法都是default方法或static方法。另外注意到boolean equals(Object obj)Object定义的方法,不算在接口方法内。因此,Comparator也是一个FunctionalInterface

    作者:crazyLL
    纯粹自己记录着玩的,来源于自己的想法或者互联网文章,侵删
  • 相关阅读:
    [USACO11JAN]Roads and Planes G【缩点+Dij+拓补排序】
    Cheatsheet: 2015 05.01 ~ 05.31
    Cheatsheet: 2015 04.01 ~ 04.30
    Cheatsheet: 2015 03.01 ~ 03.31
    Cheatsheet: 2015.02.01 ~ 02.28
    Cheatsheet: 2015 01.01~ 01.31
    Cheatsheet: 2014 12.01 ~ 12.31
    Cheatsheet: 2014 11.01 ~ 11.30
    Cheatsheet: 2014 10.01 ~ 10.30
    Cheatsheet: 2014 09.01 ~ 09.30
  • 原文地址:https://www.cnblogs.com/crazy-lc/p/14969664.html
Copyright © 2011-2022 走看看