【问题标题】:Creating new collection with calculated totals from HashSet of existing ArrayList使用现有 ArrayList 的 HashSet 计算的总数创建新集合
【发布时间】:2020-06-07 10:55:56
【问题描述】:

我正在努力解决以下问题:

我正在构建一个订单系统。我有一个 ArrayList “sales”,该列表包含一些变量和一个 HashSet,其中包含作为订单的一部分出售的商品。有一个 Part 类,其中包含部件名称 (getName) 和部件价格 (getPrice) 的吸气剂。

“销售”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

案例一

键盘 10

我该怎么做?

【问题讨论】:

  • 到目前为止你尝试过什么代码?

标签: java arraylist collections hashset


【解决方案1】:

我尝试使用HashMap<String, Integer> 为您写一些东西,其中将包含您的零件的键值对列表及其当天对应的销售数量。

希望对你有帮助:

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());
        }
    }
}

【讨论】:

  • 感谢 Petar,我包含了您的代码并对我的代码进行了一些调整,事情正朝着正确的方向发展。周末愉快。
  • 很高兴能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 2014-08-11
  • 2020-04-23
  • 2017-10-15
  • 2013-01-30
  • 2014-07-26
  • 1970-01-01
相关资源
最近更新 更多