public class PrimeNumbersCollector implements java.util.stream.Collector<Integer, Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> {
@Override
public Supplier<Map<Boolean, List<Integer>>> supplier() {
return () -> new HashMap<Boolean, List<Integer>>(){{
put(Boolean.FALSE, new ArrayList<Integer>());
put(Boolean.TRUE, new ArrayList<Integer>());
}};
}
@Override
public BiConsumer<Map<Boolean, List<Integer>>, Integer> accumulator() {
return (acc, i) -> acc.get(isPrime3(acc.get(true), i)).add(i);
}
@Override
public Function finisher() {
return Function.identity();
}
@Override
public BinaryOperator<Map<Boolean, List<Integer>>> combiner() {
return (m1, m2) -> {
m1.get(Boolean.FALSE).addAll(m2.get(Boolean.FALSE));
m1.get(Boolean.TRUE).addAll(m2.get(Boolean.TRUE));
return m1;
};
}
@Override
public Set<java.util.stream.Collector.Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(java.util.stream.Collector.Characteristics.IDENTITY_FINISH));
}
实现Collector接口
public static Map<Boolean, List<Integer>> partitionPrime2(int n){
return IntStream.rangeClosed(2, n).boxed()
.collect(new PrimeNumbersCollector());
}
public static boolean isPrime3(List<Integer> primes, int n){
int squareRoot = (int)Math.sqrt((double)n);
return takeWhile(primes, (i) -> i>n?true:false).stream().noneMatch(i -> n%i==0);
}
public static List<Integer> takeWhile(List<Integer> list, Predicate<Integer> predicate){
int i = 0;
for(Integer item : list){
if(predicate.test(item)){
return list.subList(0, i);
}
i++;
}
return list;
}
工具方法
public static void main(String[] args) {
System.out.println(partitionPrime2(100));
}
测试用例
{false=[4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100], true=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]}
运行结果
1703

被折叠的 条评论
为什么被折叠?



