1.2 方法引用

2022/1/15 23:08:42

本文主要是介绍1.2 方法引用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package ch1;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 1.2方法引用
 */
public class Sample12Test {

  /**
   * 例1-8 利用方法引用访问println方法
   */
  @Test
  public void test1_8() {
    // 使用lambda表达式
    Stream.of(3, 1, 4, 1, 5, 9).forEach(x -> System.out.println(x));
    // 使用方法引用
    Stream.of(3, 1, 4, 1, 5, 9).forEach(System.out::println);
    // 将方法引用赋给函数式接口
    Consumer<Integer> println = System.out::println;
    Stream.of(3, 1, 4, 1, 5, 9).forEach(println);
  }

  /**
   * 例1-9 在静态方法中使用方法引用
   */
  @Test
  public void test1_9() {
    Stream.generate(Math::random).limit(10).forEach(System.out::println);
  }

  /**
   * 例1-10 从类引用调用多参数实例方法
   */
  @Test
  public void test1_10() {
    List<String> strings = Arrays.asList("this", "id", "a", "list", "of", "strings");
    List<String> sorted1 = strings.stream().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList());
    System.out.println(sorted1);
    List<String> sorted2 = strings.stream().sorted(String::compareTo).collect(Collectors.toList());
    System.out.println(sorted2);
  }

  /**
   * 例1-11 使用方法引用在String上调用length方法
   */
  @Test
  public void test1_11() {
    Stream.of("this", "id", "a", "list", "of", "strings")
      //通过类名访问实例方法
      .map(String::length)
      //通过对象引用访问实例方法
      .forEach(System.out::println);
  }

  /**
   * 例1-12 方法引用的等效lambda表达式
   */
  @Test
  public void test1_12() {
    Stream.of("this", "id", "a", "list", "of", "strings")
      .map(x -> x.length())
      .forEach(x -> System.out.println(x));
  }

}



这篇关于1.2 方法引用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程