我正在尝试为Guava的ImmutableList构建Java 8 Collector实现。但我不断得到奇怪的空指针错误。我的收藏家有什么问题?
java.lang.NullPointerException at java.util.stream.ReferencePipeline.collect(未知来源)at com.swa.rm.common.test.TestLauncher.main(TestLauncher.java:50)
是我尝试运行此代码时收到的错误...
ImmutableList.of(1,5,2,7,8,2,4) .stream()。filter(i - > i%2 == 0) .collect(new ImmutableListCollector()) .forEach(i - > System.out.println(i));
调用此收集器
package com.swa.rm.common.stream;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import com.google.common.collect.ImmutableList;
public class ImmutableListCollector<T> implements Collector<T, ImmutableList.Builder<T>, ImmutableList<T>> {
@Override
public Supplier<ImmutableList.Builder<T>> supplier() {
return ImmutableList::builder;
}
@Override
public BiConsumer<ImmutableList.Builder<T>, T> accumulator() {
return (builder, t) -> builder.add(t);
}
@Override
public BinaryOperator<ImmutableList.Builder<T>> combiner() {
return (left, right) -> {
left.addAll(right.build());
return left;
};
}
@Override
public Function<ImmutableList.Builder<T>, ImmutableList<T>> finisher() {
return null;
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.UNORDERED);
}
}
UPDATE ::这是最终的实现,现在似乎可以正常工作。
import java.util.EnumSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import com.google.common.collect.ImmutableList;
public class ImmutableListCollector<T> implements Collector<T, ImmutableList.Builder<T>, ImmutableList<T>> {
@Override
public Supplier<ImmutableList.Builder<T>> supplier() {
return (() -> ImmutableList.builder());
}
@Override
public BiConsumer<ImmutableList.Builder<T>, T> accumulator() {
return (builder, t) -> builder.add(t);
}
@Override
public BinaryOperator<ImmutableList.Builder<T>> combiner() {
return (left, right) -> {
left.addAll(right.build());
return left;
};
}
@Override
public Function<ImmutableList.Builder<T>, ImmutableList<T>> finisher() {
return (b -> builder.build());
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.UNORDERED);
}
}
答案 0 :(得分:3)
您的finisher()
函数为null
;我不确定你的期望。