您的当前位置:首页正文

Java8新特性之lambda表达式

来源:图艺博知识网

一、什么是lambda表达式?

二、Java中如何使用lambda表达式

2.1 lambda表达式的形式

(函数参数列表)->{ 函数定义 }

例子:(a,b)->{a+b};
同时还有其它规则:
1.如果参数列表只有一个可以省略括号()
2.如果函数定义里面只有一个表达式,Java会默认把该表达式的计算结果作为函数返回值,可以不添加return语句。

2.2 使用lambda表达式

 /* 过滤一个目录里面的文件*/
  
File mydir = new File("d:\\dir");
// 普通写法
FileFilter  filter = new FileFilter(){
  @Override 
  public blooean accept(File file){
     if(file.getName().length()>6)
          return trure;
    return false;
  }
}
File myfiles[] = mydir.listFiles(filter);

// lambda表达式写法
File lmyfiles[] = mydir.listFiles(file -> {
  if(file.getName().length()>6){
      return true;  
  return false;
}); 
/* 很简洁有没有*/

2.3 使用lambda表达式的前提

既然lambda表达式很优秀,那么是不是可以随便用呢?当然不是的,使用lambda表达式还是得有一些要求和限制。我们以上面的例子来讲一讲。首先,看看FileFilter类的源码以及listFile方法的定义:

@FunctionalInterface
public interface FileFilter {

    /**
     * Tests whether or not the specified abstract pathname should be
     * included in a pathname list.
     *
     * @param  pathname  The abstract pathname to be tested
     * @return  <code>true</code> if and only if <code>pathname</code>
     *          should be included
     */
    boolean accept(File pathname);
}
/* listFiles方法定义 */
public File[] listFiles(FileFilter filter);

从上面我们就不难理解下面的结论:
(1)lamda表达式表示匿名函数时要和一个接口里面的函数对应(参数一致,返回类型一致)
(2)同时,该接口有且只能包含一个抽象函数的定义。

三、lambda表达式高级使用探索

未完待续。。。

Top