Java 流轉(zhuǎn)換

2018-03-12 23:23 更新

Java流轉(zhuǎn)換收集器結(jié)果


我們可以將收集器的結(jié)果轉(zhuǎn)換為不同的類型。

Collectors類的collectingAndThen()方法定義如下。

collectingAndThen(Collector<T,A,R> downstream, Function<R,RR>  finisher)

第一個(gè)參數(shù)是收集數(shù)據(jù)的收集器。 第二個(gè)參數(shù)是轉(zhuǎn)換結(jié)果的轉(zhuǎn)換器。

例子

以下代碼返回收集數(shù)據(jù)的不可更改視圖。

import java.time.LocalDate;
import java.time.Month;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
  public static void main(String[] args) {
    List<String> names = Employee.persons()
        .stream()
        .map(Employee::getName)
        .collect(Collectors.collectingAndThen(Collectors.toList(),
             result ->  Collections.unmodifiableList(result))); 
    System.out.println(names);
  }
}

class Employee {
  public static enum Gender {
    MALE, FEMALE
  }

  private long id;
  private String name;
  private Gender gender;
  private LocalDate dob;
  private double income;

  public Employee(long id, String name, Gender gender, LocalDate dob,
      double income) {
    this.id = id;
    this.name = name;
    this.gender = gender;
    this.dob = dob;
    this.income = income;
  }

  public String getName() {
    return name;
  }
  public static List<Employee> persons() {
    Employee p1 = new Employee(1, "Jake", Gender.MALE, LocalDate.of(1971,
        Month.JANUARY, 1), 2343.0);
    Employee p2 = new Employee(2, "Jack", Gender.MALE, LocalDate.of(1972,
        Month.JULY, 21), 7100.0);
    Employee p3 = new Employee(3, "Jane", Gender.FEMALE, LocalDate.of(1973,
        Month.MAY, 29), 5455.0);
    Employee p4 = new Employee(4, "Jode", Gender.MALE, LocalDate.of(1974,
        Month.OCTOBER, 16), 1800.0);
    Employee p5 = new Employee(5, "Jeny", Gender.FEMALE, LocalDate.of(1975,
        Month.DECEMBER, 13), 1234.0);
    Employee p6 = new Employee(6, "Jason", Gender.MALE, LocalDate.of(1976,
        Month.JUNE, 9), 3211.0);

    List<Employee> persons = Arrays.asList(p1, p2, p3, p4, p5, p6);

    return persons;
  }
}

上面的代碼生成以下結(jié)果。



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)