[英]Decrease two custom objects values using reduce operation
我有一個自定義 object,如下所示。
public class Count {
private int words;
private int characters;
//getters & setters && all args constructor
void Count decrease(Count other) {
this.words -= other.words;
this.characters -= other.characters;
return this;
}
}
我想達到下一個結果,例如:
計數 book1 = new Count(10, 35);
計數 book2 = new Count(6, 10);
結果將是:Count result = Count(4, 25) -> ([10-6], [35-10])
我嘗試了這個解決方案,但沒有奏效。
Stream.of(book1, book2).reduce(new CountData(), CountData::decrease)
可以使用減少操作或 java >=8 的另一個 stream 操作來實現此結果?
以下臨時解決方案使用book2
的單元素 stream 從使用book1
值初始化的種子中減去:
Count reduced = Stream.of(book2)
.reduce(new Count(book1.getWords(), book1.getCharacters()), Count::decrease);
這里book1
的值不受影響。
但是,對於這種特定情況,這可以在沒有 Stream API 的情況下完成:
Count reduced = new Count(book1.getWords(), book1.getCharacters())
.decrease(book2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.