一、Collector接口解读:
Collector接口解读:
1 public interface Collector<T, A, R> { 2 Supplier<A> supplier(); 3 BiConsumer<A, T> accumulator(); 4 BinaryOperator<A> combiner(); 5 Function<A, R> finisher(); 6 Set<Characteristics> characteristics(); 7 }
Collector<T, A, R>
T: stream中的元素类型;
A:累加器的类型,可以想象成一个容器。比如T要累加,转化为List<T>,A就是List类型。
R:最终返回值类型
T is the generic type of the items in the stream to be collected.
A is the type of the accumulator, the object on which the partial result will be accumulated during the collection process.
R is the type of the object(typically, but not always, the collection) resulting from the collect operation.
二、自定义Collector,看看是怎么实现的
仿照Collectors.toList,自定义实现一个Collector的接口:
1 package com.cy.java8; 2 3 import java.util.*; 4 import java.util.function.BiConsumer; 5 import java.util.function.BinaryOperator; 6 import java.util.function.Function; 7 import java.util.function.Supplier; 8 import java.util.stream.Collector; 9 10 public class ToListCollector<T> implements Collector<T, List<T>, List<T>> { 11 12 private void log(final String s){ 13 System.out.println(Thread.currentThread().getName() + "-" + s); 14 } 15 16 @Override 17 public Supplier<List<T>> supplier() { 18 log("supplier"); 19 return ArrayList::new; 20 } 21 22 @Override 23 public BiConsumer<List<T>, T> accumulator() { 24 log("accumulator"); 25 return (list, v) -> list.add(v); 26 } 27 28 @Override 29 public BinaryOperator<List<T>> combiner() { 30 log("combiner"); 31 return (left, right) -> { 32 left.addAll(right); 33 return left; 34 }; 35 } 36 37 @Override 38 public Function<List<T>, List<T>> finisher() { 39 log("finisher"); 40 return Function.identity(); 41 } 42 43 @Override 44 public Set<Characteristics> characteristics() { 45 log("characteristics"); 46 return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH, 47 Collector.Characteristics.CONCURRENT)); 48 } 49 }
测试执行:
1 package com.cy.java8; 2 3 import java.util.Arrays; 4 import java.util.List; 5 import java.util.stream.Collector; 6 7 public class CustomCollectorAction { 8 9 public static void main(String[] args) { 10 Collector<String, List<String>, List<String>> collector = new ToListCollector<>(); 11 12 String[] array = new String[]{"Java 8", "Hello", "Collector", "Custom", "Stream"}; 13 14 List<String> list1 = Arrays.stream(array).filter(s -> s.length()>5).collect(collector); 15 System.out.println(list1); 16 17 List<String> list2 = Arrays.stream(array).parallel().filter(s -> s.length()>5).collect(collector); 18 System.out.println(list2); 19 } 20 21 }
console:
main-supplier
main-accumulator
main-combiner
main-characteristics
main-characteristics
[Java 8, Collector, Custom, Stream]
main-characteristics
main-characteristics
main-supplier
main-accumulator
main-combiner
main-characteristics
main-characteristics
[Java 8, Collector, Custom, Stream]
---