Java教程

1.3 构造函数引用

本文主要是介绍1.3 构造函数引用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package ch1;

import org.junit.jupiter.api.Test;

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

/**
 * 1.3构造函数引用
 */
public class Sample13Test {

  /**
   * 例1-13 将人员列表转换为姓名列表
   */
  @Test
  public void test1_13() {
    List<Person> people = Arrays.asList(
      new Person("张三"),
      new Person("李四"),
      new Person("王五")
    );
    //List<String> names = people.stream().map(person -> person.getName()).collect(Collectors.toList());
    // 或采用以下方案
    List<String> names = people.stream().map(Person::getName).collect(Collectors.toList());
    System.out.println(names);
  }

  /**
   * 例1-15 将字符串转为Person实例
   */
  @Test
  public void test1_15() {
    List<String> names = Arrays.asList("张三", "李四", "王五");
//    List<Person> people = names.stream().map(name -> new Person(name)).collect(Collectors.toList());
    List<Person> people = names.stream().map(Person::new).collect(Collectors.toList());
    System.out.println(people);
  }

  /**
   * 例1-17 将列表转为流,再转换回列表
   */
  @Test
  public void test1_17() {
    Person before = new Person("张三");
    List<Person> people = Stream.of(before).collect(Collectors.toList());
    Person after = people.get(0);
    System.out.println(before == after); //true
    before.setName("李四");
    System.out.println(before == after); //true
  }

  /**
   * 例1-18 将列表转为流,再转换回列表
   */
  @Test
  public void test1_18() {
    Person before = new Person("张三");
    List<Person> people = Stream.of(before).map(Person::new).collect(Collectors.toList());
    Person after = people.get(0);
    System.out.println(before == after); //false
    before.setName("李四");
    System.out.println(before == after); //false
  }

}

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