lambda表达式替换

基本语法:

(parameters) -> expression

或者 

(parameters) ->{ statements; }

简单举个栗子:

public class ThreadTest {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello you !");
            }
        }).start();

// 函数式接口(只有一个方法的接口)可以用    lambda表达式    替换
        new Thread(() -> System.out.println("hello me !")).start();
    }
}

 排序

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;

public class ArraysTest {
    public static void main(String[] args) {
        String[]  players = {"yellow","blue","red","black"};
//        排序1
//        Arrays.sort(players);

//       排序2
//        Arrays.sort(players, new Comparator() {
//            @Override
//            public int compare(String o1, String o2) {
//                return o1.compareTo(o2);
//            }
//        });

        //lambda表达式
//        排序3:根据字母表排序
        Arrays.sort(players,((o1, o2) -> o1.compareTo(o2)));
        //结果:
        //black
        //blue
        //red
        //yellow


//          根据name长度排序
//        Arrays.sort(players,((String o1,String o2) -> o1.length()-o2.length()));
        //结果:
        //red
        //blue
        //black
        //yellow


//        根据最后一个字母排序
//        Arrays.sort(players,((String o1,String o2) -> o1.charAt(o1.length()-1)-o2.charAt(o2.length()-1)));
        //结果:
        //red
        //blue
        //black
        //yellow






        for(int i = 0;i < players.length;i++) {
            System.out.println(players[i]);
        }
    }

}

方法引用,使用双引号::

有一个苹果的List,现在需要根据苹果的重量进行排序。List 的 sort 函数接收一个 Comparator 类型的参数,Comparator 是一个函数式接口,接收两个参数,返回一个int值。

(1)静态方法引用

Apple的静态方法compareByWeight正好符合Comparator函数式接口,所以可以使用:

Apple::compareByWeight 静态方法引用来替代lambda表达式

实体类Apple

public class Apple {
    private String name;
    private String color;
    private Double weight;

    public Apple(String name, String color, Double weight) {
        this.name = name;
        this.color = color;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Double getWeight() {
        return weight;
    }

    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", weight=" + weight +
                '}';
    }

    public static int compareByWeight(Apple a1,Apple a2){
        double v = a1.getWeight() - a2.getWeight();
        int i = new Double(v).intValue();
        return i;
    }
}

测试类AppleTest

import java.util.Arrays;
import java.util.List;

/**
 * 静态方法引用
 */
public class AppleTest {
    public static void main(String[] args) {
        Apple apple1 = new Apple("红富士", "Red", 280d);
        Apple apple2 = new Apple("蛇果", "Yello", 470d);
        Apple apple3 = new Apple("blue", "Red", 320d);
        Apple apple4 = new Apple("pink", "Green", 300d);
        List apples = Arrays.asList(apple1, apple2, apple3, apple4);
//        lambda表达式
//        apples.sort((Apple a1,Apple a2) -> {
//            return new Double(a1.getWeight()- a2.getWeight()).intValue();
//        });

//        静态方法引用形式
        apples.sort(Apple::compareByWeight);

//        遍历输出
        apples.forEach(apple -> System.out.println(apple));
        //结果:
        //Apple{name='红富士', color='Red', weight=280.0}
        //Apple{name='pink', color='Green', weight=300.0}
        //Apple{name='blue', color='Red', weight=320.0}
        //Apple{name='蛇果', color='Yello', weight=470.0}
    }
//    注意:Apple.compareByWeight是方法的调用,而Apple::compareByWeight方法引用,这两者完全不是一回事。
}

(2)实例方法引用

实体类Apple

public class Apple {
    private String name;
    private String color;
    private Double weight;

    public Apple(String name, String color, Double weight) {
        this.name = name;
        this.color = color;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Double getWeight() {
        return weight;
    }

    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", weight=" + weight +
                '}';
    }
//    实例方法
    public static class AppleComparator{
    public int compareByWeight(Apple a1,Apple a2){
        double v = a1.getWeight() - a2.getWeight();
        int i = new Double(v).intValue();
        return i;
    }
    }
}

测试类AppleTest2

import java.util.Arrays;
import java.util.List;

/**
 * 实例方法引用
 */
public class AppleTest2 {
    public static void main(String[] args) {
        Apple apple1 = new Apple("红富士", "Red", 280d);
        Apple apple2 = new Apple("蛇果", "Yello", 100d);
        Apple apple3 = new Apple("blue", "Red", 320d);
        Apple apple4 = new Apple("pink", "Green", 300d);
        List apples = Arrays.asList(apple1, apple2, apple3, apple4);
//        lambda表达式
//        apples.sort((Apple a1,Apple a2) -> {
//            return new Double(a1.getWeight()- a2.getWeight()).intValue();
//        });

//        实例方法引用形式
        Apple.AppleComparator appleComparator = new Apple.AppleComparator();
        apples.sort(appleComparator::compareByWeight);


//        遍历输出
        apples.forEach(apple -> System.out.println(apple));
        //结果:
        //Apple{name='蛇果', color='Yello', weight=100.0}
        //Apple{name='红富士', color='Red', weight=280.0}
        //Apple{name='pink', color='Green', weight=300.0}
        //Apple{name='blue', color='Red', weight=320.0}
    }

}

(3)类方法引用

实体类Apple

public class Apple {
    private String name;
    private String color;
    private Double weight;

    public Apple(String name, String color, Double weight) {
        this.name = name;
        this.color = color;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Double getWeight() {
        return weight;
    }

    public void setWeight(Double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", weight=" + weight +
                '}';
    }
    public int compareByWeight(Apple other) {
        double v = this.getWeight() - other.getWeight();
        return new Double(v).intValue();
    }
}

测试类AppleTest3

import java.util.Arrays;
import java.util.List;

/**
 * 类方法引用
 */
public class AppleTest3 {
    public static void main(String[] args) {
        Apple apple1 = new Apple("红富士", "Red", 150d);
        Apple apple2 = new Apple("蛇果", "Yello", 470d);
        Apple apple3 = new Apple("blue", "Red", 320d);
        Apple apple4 = new Apple("pink", "Green", 400d);
        List apples = Arrays.asList(apple1, apple2, apple3, apple4);
//        lambda表达式
//        apples.sort((Apple a1,Apple a2) -> {
//            return new Double(a1.getWeight()- a2.getWeight()).intValue();
//        });

//        类方法引用形式
        apples.sort(Apple::compareByWeight);

//        遍历输出
        apples.forEach(apple -> System.out.println(apple));
        //结果:
        //Apple{name='红富士', color='Red', weight=150.0}
        //Apple{name='blue', color='Red', weight=320.0}
        //Apple{name='pink', color='Green', weight=400.0}
        //Apple{name='蛇果', color='Yello', weight=470.0}
    }
//    这里使用的是:类名::实例方法名。首先要说明的是,方法引用不是方法调用。compareByWeight一定是某个实例调用的,就是lambda表达式的第一个参数,然后lambda表达式剩下的参数作为 compareByWeight的参数,这样compareByWeight正好符合lambda表达式的定义。
//    或者也可以这样理解:
//    (Apple a1, Apple a2) -> { return new Double(a1.getWeight() - a2.getWeight()).intValue(); }
//    int compareByWeight(Apple other) 需要当前对象调用,然后与另外一个对象比较,并且返回一个int值。可以理解为lambda表达式的第一个参数 a1 赋值给当前对象, 然后 a2 赋值给 other对象,然后返回int值。
}

(4)构造方法引用

import com.google.common.base.Supplier;

/**
 *构造方法引用
 */
public class ConstructionMethodTest {
    int age;

    public ConstructionMethodTest() {
        System.out.println("...." + age);
    }

    public static void main(String[] args) {
        Supplier aNew = ConstructionMethodTest::new;
        aNew.get();
        aNew.get();

    }
//  结果:
//    ....0
//    ....0

}

 

你可能感兴趣的:(java)