您的位置:首页 > 编程语言 > Java开发

Java新特性-Lambda表达式入门

2017-08-18 09:03 531 查看
假设我们现在来写一个依据不同属性来筛选苹果的方法,代码如下:

Predicate接口代码如下:

package java8Test;

/**
*
* @ClassName: Predicate
* @Description:函数式接口:就是只定义一个抽象方法的接口
* @author cheng
* @date 2017年8月17日 上午9:00:59
*/
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}


筛选方法:

/**
*
* @Title: filterApples
* @Description: 筛选方法
* @param inventory
* @param p
* @return
*/
public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p) {
List<Apple> result = new ArrayList<Apple>();
for (Apple apple : inventory) {
if (p.test(apple)) {//调用接口中的方法
result.add(apple);
}
}
return result;
}


第一种方式:实现接口

实现Predicate接口,代码如下:

package java8Test;

/**
*
* @ClassName: AppleColorPredicate
* @Description:筛选苹果颜色
* @author cheng
* @date 2017年8月17日 下午5:20:17
*/
public class AppleColorPredicate implements Predicate<Apple> {

/**
* 筛选颜色
*/
@Override
public boolean test(Apple apple) {
return "green".equals(apple.getColor());
}

}


调用filterApples方法,代码如下:

filterApples(inventory, new AppleColorPredicate());


不足之处:随着筛选条件的增加,实现接口的类越来越多

第二种方式:匿名内部类

直接使用匿名内部类,代码如下:

filterApples(inventory, new Predicate<Apple>() {

/**
* 重写test方法
*/
@Override
public boolean test(Apple apple) {
return "green".equals(apple.getColor());
}

});


不足之处:模板化代码太多,核心代码就一句:“green”.equals(apple.getColor());

第三种方式:Lambda表达式

使用Lambda表达式,代码如下:

filterApples(inventory, (Apple apple) -> "green".equals(apple.getColor()));


分析:

上面代码中的filterApples方法,其中有一个为Predicate接口类型的参数,传入这个接口的引用,实质上是为了调用Predicate接口里的方法,现在由于Predicate接口中只有一个方法,即test方法.所以传入这个接口的引用参数实质上是为了调用Predicate接口中的test方法.这里使用的Lambda表达式,其实就是重写filterApples接口中的test方法.使用Lambda表达式直接实现了代码的传递,从而达到了行为参数化的目的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息