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
  }

}

上一篇:406.根据身高重建队列


下一篇:Linux内存映射原理