[英]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.