首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从现有ArrayList的HashSet创建具有计算合计的新集合

从现有ArrayList的HashSet创建具有计算合计的新集合
EN

Stack Overflow用户
提问于 2020-02-24 02:09:43
回答 1查看 36关注 0票数 0

我正在为以下问题而苦苦挣扎:

我正在建立一个订单系统。我有一个ArrayList "sales",该列表包含一些变量和一个包含作为订单一部分销售的商品的HashSet。有一个Part类,其中包含零件名称(getName)和零件价格(getPrice)的getter。

"sales“ArrayList包含:(int orderNumber, LocalDate date, OrderItem orderItem)

看起来像这样:

订单: 1,日期: 2020-02-23,物料:部件:显示器,数量: 3,部件: CPU,数量:2

订单: 2,日期: 2020-02-23,项目:部件:耳机,数量: 1,部件:外壳,数量:1

订单: 3,日期: 2020-02-23,项目:部件: CPU,数量: 10,部件:键盘,数量: 10

每个OrderItem包含:(Part part, int quantity)。Part类包含(String partName, double price)

我想要做的是创建一个新的集合,列出一天中售出的部件总数,如下所示:

监视器3

CPU 12

头戴式耳机1

案例1

键盘10

我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2020-02-24 02:27:03

我试图使用HashMap<String, Integer>为您编写一些内容,它将包含部件及其当天相应售出数量的键值对列表。

希望它能有所帮助:

代码语言:javascript
复制
public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<>();
    for (Orderitem item: listOfOrderItems) { // here you need to get a list of your ordered items for the day
        Part part = item.getPart(); // here you need some form of a getter to access the given part from the given Orderitem
        String partName = part.getName();
        if (!map.containsKey(partName)) {
            map.put(partName, item.getQuantity());
        } else {
            map.put(partName, map.get(partName) + item.getQuantity());
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60365284

复制
相关文章

相似问题

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