Java教程

1.1 lambda表达式

本文主要是介绍1.1 lambda表达式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package ch1;

import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;

/**
 * 1.1lambda表达式
 */
public class Sample11Test {

  /**
   * 例1-1 使用匿名内部类
   */
  @Test
  public void test1_1() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("inside runable using an anonymous inner class");
      }
    }).start();
  }

  /**
   * 例1-2 在上述的例子中使用lambda表达式
   */
  @Test
  public void test1_2() {
    new Thread(() -> System.out.println("inside Thread constructor using lambda")).start();
  }

  /**
   * 例1-3 将lambda表达式赋给变量
   */
  @Test
  public void test1_3() {
    Runnable r = () -> System.out.println("lambda expression implementing the run method");
    new Thread(r).start();
  }

  /**
   * 例1-4 FilenameFilter的匿名内部类实现
   */
  @Test
  public void test1_4() {
    File directory = new File("./src/main/java/ch1");
    System.out.println(directory.getAbsolutePath());
    String[] names = directory.list(new FilenameFilter() {
      @Override
      public boolean accept(File dir, String name) {
        return name.endsWith(".java");
      }
    });
    System.out.println(Arrays.asList(names));
  }

  /**
   * 例1-5 FilenameFilter 接口的lambda表达式实现
   */
  @Test
  public void test1_5() {
    File directory = new File("./src/main/java/ch1");
    String[] names = directory.list(((dir, name) -> name.endsWith(".java")));
    System.out.println(Arrays.asList(names));
  }

  /**
   * 例1-6 具有显示数据类型的lambda表达式
   */
  @Test
  public void test1_6() {
    File directory = new File("./src/main/java/ch1");
    String[] names = directory.list(((File dir, String name) -> name.endsWith(".java")));
    System.out.println(Arrays.asList(names));
  }

  /**
   * 例1-7 lambda代码块
   */
  @Test
  public void test1_7() {
    File directory = new File("./src/main/java/ch1");
    String[] names = directory.list(((File dir, String name) -> {
      return name.endsWith(".java");
    }));
    System.out.println(Arrays.asList(names));
  }

}

这篇关于1.1 lambda表达式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!