我有一个自定义对象,如下所示。
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 =新计数(10,35);
计数book2 =新计数(6,10);
结果是:计数结果=计数(4,25) -> (10-6,35-10)
我试过这个解决方案,但没成功。
Stream.of(book1, book2).reduce(new CountData(), CountData::decrease)
是否可以使用>=8的减约操作或其他流操作来实现此结果?
发布于 2021-12-08 22:24:29
以下特殊解决方案使用book2
的单个元素流从用book1
值初始化的种子中减去:
Count reduced = Stream.of(book2)
.reduce(new Count(book1.getWords(), book1.getCharacters()), Count::decrease);
这里,book1
的值不受影响。
但是,对于这种特殊情况,可以不使用Stream来完成:
Count reduced = new Count(book1.getWords(), book1.getCharacters())
.decrease(book2);
https://stackoverflow.com/questions/70281824
复制相似问题