java 为什么T reduce(T,BinaryOperator)不允许静态方法引用,而reduce(U,BiFunction,BinaryOperator)允许?

m0rkklqb  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(158)

下面定义的流API中有2个和3个arg版本的reduce

T reduce(T identity,
         BinaryOperator<T> accumulator)

字符串

<U> U reduce(U identity,
             BiFunction<U,? super T,U> accumulator,
             BinaryOperator<U> combiner)


我尝试用stream/parallel stream来计算一个句子中的单词数量,并使用累加器和合并器创建以下类

class WordCounter {
    private final int counter;
    private final boolean lastSpace;

    // constructor skipped

    public WordCounter accumulate(Character c) {
        if (Character.isWhitespace(c)) {
            return lastSpace ?
                    this :
                    new WordCounter(counter, true);
        } else {
            return lastSpace ?
                    new WordCounter(counter + 1, false) :
                    this;
        }
    }

    public WordCounter combine(WordCounter wordCounter) {
        return new WordCounter(counter + wordCounter.counter, wordCounter.lastSpace);
    }
}


现在我试着在main方法中用reduce的版本来测试它

public static void main(String[] args) {
        String SENTENCE = "please help";

        Stream<Character> stream = IntStream
                .range(0, SENTENCE.length())
                .mapToObj(SENTENCE::charAt);

        int count2 = stream.reduce(new WordCounter(0, true),
                WordCounter::accumulate
        ).getCounter();
}


当我尝试上面的方法时,编译器会抱怨,因为我正在使用来自static main的非静态WordCounter::accumulate
但是,在同一个静态main中,

int count1 = stream.reduce(new WordCounter(0, true),
                WordCounter::accumulate,
                WordCounter::combine
        ).getCounter();

clj7thdc

clj7thdc1#

一个BinaryOperator<T>相当于一个BiFunction<T, T, T>。在你的例子中,它需要两个WordCounter示例并返回一个WordCounter示例。WordCounter::combine将是有效的,但不是WordCounter::accumulate
第二个reduce方法不要求两个输入类型相同。这意味着WordCounter::accumulate被解析为允许的BiFunction<WordCounter, Character, WordCounter>-UWordCounterTCharacter

相关问题