App下載
首頁(yè)javastream_collectorJava Stream - 如何從供應(yīng)商,蓄能器,組合器和整理器創(chuàng)建收集器

Java Stream - 如何從供應(yīng)商,蓄能器,組合器和整理器創(chuàng)建收集器

我們想知道如何從供應(yīng)商,蓄能器,組合器和整理器創(chuàng)建收集器。
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collector;

public class Main {

  public static void main(String[] args) throws Exception {
    List<Person> persons =
        Arrays.asList(
            new Person("Max", 18),
            new Person("Peter", 23),
            new Person("Pamela", 23),
            new Person("David", 12));   

    Collector<Person, StringJoiner, String> personNameCollector =
        Collector.of(
            () -> new StringJoiner(" | "),          // supplier
            (j, p) -> j.add(p.name.toUpperCase()),  // accumulator
            (j1, j2) -> j1.merge(j2),               // combiner
            StringJoiner::toString);                // finisher

    String names = persons
        .stream()
        .collect(personNameCollector);

    System.out.println(names);
  }

}
class Person {
  String name;
  int age;

  Person(String name, int age) {
      this.name = name;
      this.age = age;
  }

  @Override
  public String toString() {
      return name;
  }
}