首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用约简操作减少两个自定义对象值

使用约简操作减少两个自定义对象值
EN

Stack Overflow用户
提问于 2021-12-08 21:16:58
回答 1查看 135关注 0票数 0

我有一个自定义对象,如下所示。

代码语言:javascript
运行
复制
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的减约操作或其他流操作来实现此结果?

EN

回答 1

Stack Overflow用户

发布于 2021-12-08 22:24:29

以下特殊解决方案使用book2的单个元素流从用book1值初始化的种子中减去:

代码语言:javascript
运行
复制
Count reduced = Stream.of(book2)
    .reduce(new Count(book1.getWords(), book1.getCharacters()), Count::decrease);

这里,book1的值不受影响。

但是,对于这种特殊情况,可以不使用Stream来完成:

代码语言:javascript
运行
复制
Count reduced = new Count(book1.getWords(), book1.getCharacters())
        .decrease(book2);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70281824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档