下面定义的流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();
型
1条答案
按热度按时间clj7thdc1#
一个
BinaryOperator<T>
相当于一个BiFunction<T, T, T>
。在你的例子中,它需要两个WordCounter
示例并返回一个WordCounter
示例。WordCounter::combine
将是有效的,但不是WordCounter::accumulate
。第二个
reduce
方法不要求两个输入类型相同。这意味着WordCounter::accumulate
被解析为允许的BiFunction<WordCounter, Character, WordCounter>
-U
是WordCounter
,T
是Character
。