1. 程式人生 > >java8之lambda表達式(1)-基本語法

java8之lambda表達式(1)-基本語法

com nal called new collect starting 代碼 face 使用

參考:http://www.cnblogs.com/andywithu/p/7344507.html

lambda表達式,即帶有參數的表達式,為更清晰地理解lambda表達式,先看如下例子: (1) 技術分享
class Student{
    private String name;
    private Double score;
 
    public Student(String name, Double score) {
        this.name = name;
        this.score = score;
    }
 
    public String getName() {
        return name;
    }
 
    public Double getScore() {
        return score;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public void setScore(Double score) {
        this.score = score;
    }
 
    @Override
    public String toString() {
        return "{"
                + "\"name\":\"" + name + "\""
                + ", \"score\":\"" + score + "\""
                + "}";
    }
}
 
@Test
public void test1(){
    List<Student> studentList = new ArrayList<Student>(){
        {
            add(new Student("stu1",100.0));
            add(new Student("stu2",97.0));
            add(new Student("stu3",96.0));
            add(new Student("stu4",95.0));
        }
    };
    Collections.sort(studentList, new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return Double.compare(o1.getScore(),o2.getScore());
        }
    });
    System.out.println(studentList);
}
技術分享 (1)中代碼調用Collections.sort方法對集合進行排序,其中第二個參數是一個類,準確地說是一個匿名內部類,sort方法調用內部類中的compare方法對list進行位置交換,因為java中的參數類型只能是類或者基本數據類型,所以雖然傳入的是一個Comparator類,但是實際上需要傳遞的僅僅是compare方法,lambda表達式專門針對只有一個方法的接口(即函數式接口),Comparator就是一個函數式接口
@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}
@FunctionalInterface的作用就是標識一個接口為函數式接口,此時Comparator裏只能有一個抽象方法。 使用lambda表達式之後(1)中的代碼改造如下 (2) 技術分享
public void test1_(){
        List<Student> studentList = new ArrayList<Student>(){
            {
                add(new Student("stu1",100.0));
                add(new Student("stu2",97.0));
                add(new Student("stu3",96.0));
                add(new Student("stu4",95.0));
            }
        };
        Collections.sort(studentList,(s1,s2)-> Double.compare(s1.getScore(),s2.getScore()));
        System.out.println(studentList);
    }
技術分享 對於有多個參數的情況,語法: 1. ambda表達式的基本格式為(x1,x2)->{表達式...}; 2. 在上式中,lambda表達式帶有兩個參數,因此兩邊的括號不能省略,而參數類型可以省略 3. 如果表達式只有一行,那麽表達式兩邊的花括號可以省略 另外一個常見的例子是新建一個線程,不使用lambda表達式的寫法為 (3) 技術分享
public void testThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello, i am thread!");
            }
        }).start();
    }
技術分享 其中Runnable接口也是一個函數式接口,源碼如下 技術分享
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object‘s
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
技術分享 將其轉換為lambda表達式的寫法為 (4)
public void testThread_(){
    new Thread(()-> System.out.println("hello, i am thread!")).start();
}
對於沒有參數的情況 ,語法: 1.參數的括號不能省略,如果只有一句的表達式則可省略花括號和語句結尾的分號 我們構造一個只有一個參數的函數式接口 技術分享
@FunctionalInterface
public interface MyFunctionalInterface {
    public void single(String msg);
}
 
/**
 * 需要單個參數
 */
public static void testOnePar(MyFunctionalInterface myFunctionalInterface){
    myFunctionalInterface.single("msg");
}
 
/**
     * 一個參數,可以省略參數的括號
     */
    @Test
    public void testOneParameter(){
        testOnePar(x-> System.out.println(x));
    }
技術分享 對於只有一個參數的情況 ,語法: 1.參數的括號可以省略 在這裏我們為了演示只有一個參數的情況自己創建了一個函數式接口,其實java8中已經為我們提供了很多常見的函數式接口 技術分享 常見的有 Function:提供任意一種類型的參數,返回另外一個任意類型返回值。 R apply(T t); Consumer:提供任意一種類型的參數,返回空值。 void accept(T t); Supplier:參數為空,得到任意一種類型的返回值。T get(); Predicate:提供任意一種類型的參數,返回boolean返回值。boolean test(T t); 因此針對上面的情況,我們可以直接使用Consumer類,
/**
     * 需要單個參數
     */
    public static void testOnePar1(Consumer unaryOperator){
        unaryOperator.accept("msg");
    }

java8之lambda表達式(1)-基本語法