-1

我有一个问题,因为我有一个包含多种类型的产品列表,但是,我想显示一般数据,但它在列表中重复了,现在我可以让它们只存在一次,但问题是当我想要当元素已经存在于我的哈希中时设置结果,它不做设置,我不知道它是否与 Java 的浅拷贝有关,我尝试了 Cloneable 但它没有成功。

  @RequiresApi(api = Build.VERSION_CODES.N)
  public List<ProductsAlmacenInfo> getProductsTotal() {
    HashMap<Long, ProductsAlmacenInfo> map = new HashMap<Long, ProductsAlmacenInfo>();
    for (ProductsAlmacenInfo x: products) {
      ProductsAlmacenInfo temp = x;
      if(map.containsKey(x.getId_product().toString()) && (x.getStock_type().contentEquals("VTA") ||
              x.getStock_type().contentEquals("VDO") || x.getStock_type().contentEquals("CHG"))) {
        temp.setQty(Math.abs(x.getQty()+1));
        map.replace(temp.getId_product(), temp);
      }
      else if (!map.containsKey(x.getId_product().toString())) {
        temp.setQty(Math.abs(x.getQty()));
        map.put(x.getId_product(), temp);
      }
    }
    List<ProductsAlmacenInfo> productsTemp = new ArrayList<ProductsAlmacenInfo>(map.values());
    if(productsTemp.isEmpty())  return products;
    return productsTemp;
  }[enter image description here][1]
4

1 回答 1

0

要插入新条目或与现有条目组合,请使用以下merge()方法:

HashMap<Long, ProductsAlmacenInfo> map = new HashMap<>();
for (ProductsAlmacenInfo x : products) {
    x.setQty(Math.abs(x.getQty())); // Why?

    map.merge(x.getId_product(), x, (a, b) -> {
        ProductsAlmacenInfo temp = b.clone(); // or use copy-constructor
                                              // or don't copy if not needed
        temp.setQty(a.getQty() + b.getQty());
        return temp;
    });
}

id_product除了和之外的所有属性qty都将具有来自最后一个对象的值id_product。如果您想从第一个看到的对象中获取值,请使用 clonea而不是b.

于 2020-04-02T22:37:32.217 回答