案例:接收
第一种方式自定义收集器第一步:实现收集器接口,重写收集器方法,以及定义业务逻辑方法
package com.java8.CustomCollector;
import java.util.*;
import java.util.function.*;
import java.util.
public class PrimeNumbersCollector implements Collector>,Map>>{
/**
* 作用:创建结果容器
* @return
*/
@Overr
}
第二步:应用方法与java8内置收集归约函数做对比
package com.java8.CustomCollector;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.partitioningBy;
public class Test {
public static void main(String[] arg){
long fastest = Long.MAX_VALUE;
for(int i = 0; i < 10 ;i++){
long s
}
函数输出(提高了55%)
Fastest execution done in 865 msecs
CustomCollector Fastest execution done in 382 msecs
第二种方式实现自定义收集器把实现核心逻辑的三个函数传给collect方法的重载版本来获得同样的结果。
package com.java8.CustomCollector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.partitioningBy;
public class Test {
public static void main(String[] arg){
long fastest = Long.MAX_VALUE;
for(int i = 0; i < 10 ;i++){
long start = System.nanoTime();
partitionPaimesWithCustomCollector(1000000);
long duration = (System.nanoTime() - start) / 1000000;
if (duration < fastest ) fastest = duration;
}
System.out.println("CustomCollector Fastest execution done in " + fastest +" msecs");
}
/**
* 自定义收集器调用
* @param n
* @return
*/
public static Map> partitionPaimesWithCustomCollector(int n){
return IntStream.rangeClosed(2,n).boxed().collect(
()->new HashMap>(){{
put(true,new ArrayList<>());
put(false,new ArrayList<>());
}},
(acc,candidate) ->{
acc.get(isPrime(acc.get(true)
,candidate)
).add(candidate);
},
(map1,map2) ->{
map1.get(true).addAll(map2.get(true));
map1.get(false).addAll(map2.get(false));
});
}
public static List takeWhile(List list, Predicate p){
int i = 0;
for(A item : list){
if(!p.test(item)){
return list.subList(0,i);
}
i++;
}
return list;
}
public static boolean isPrime(List primes,int candidate){
int candidateRoot = (int)Math.sqrt((double)candidate);
return takeWhile(primes,i -> i <= candidateRoot).stream().noneMatch(p ->candidate % p == 0);
}
}
收获:可以自己需要的时候