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

问题描述 投票:0回答:1

下面定义的流 API 中有 2 个和 3 个参数版本的

reduce

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

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

我正在尝试使用流/并行流来计算句子中的单词数,并使用以下带有累加器和组合器的类

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

现在我正在尝试使用reduce版本在main方法中进行测试

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

当我尝试上述操作时,编译器会抱怨,因为我正在使用静态 main 中的非静态

WordCounter::accumulate

但是,在同一个静态主文件中,以下内容可以工作

int count1 = stream.reduce(new WordCounter(0, true), WordCounter::accumulate, WordCounter::combine ).getCounter();
    
java java-8 java-stream
1个回答
0
投票
A

BinaryOperator<T>

 相当于 
Function<T, T, T>
。在您的情况下,它需要采用两个 
WordCounter
 实例并返回一个 
WordCounter
 实例。 
WordCounter::combine
 有效,但 
WordCounter::accumulate
 无效。

第二种

reduce

方法不需要两种输入类型相同。这意味着 
WordCounter::accumulate
 被解析为 
BiFunction<WordCounter, Character, WordCounter>
,这是允许的 - 
U
WordCounter
T
Character

© www.soinside.com 2019 - 2024. All rights reserved.