gpt4 book ai didi

java - 我的 ImmutableList 收集器不工作?

转载 作者:行者123 更新时间:2023-11-29 05:14:55 24 4
gpt4 key购买 nike

我正在尝试为 Guava 的 ImmutableList 构建一个 Java 8 收集器实现。但是我不断收到奇怪的空指针错误。我的收集器出了什么问题?

java.lang.NullPointerException at java.util.stream.ReferencePipeline.collect(Unknown Source) 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);
}

}

更新:这是最终的实现,现在似乎可以工作了。

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);
}

}

最佳答案

您的finisher() 函数是null;我不确定您的期望是什么。

关于java - 我的 ImmutableList 收集器不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26934042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com