Search code examples
javaandroid-studiohashmap

HashMap List problems updating the value of an item in Java


I am having a problem since I have a list of products which contains several types, however, I want to show the general data but it was repeated in the list, now I can make them only exist once but the problem is that when I want to set the result when the element already existed in my Hash, it doesn't do the set, I don't know if it has to do with the Shallow Copy of Java, I tried Cloneable but it didn't succeed.

  @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]

Solution

  • To insert a new entry or combine with existing entry, use the merge() method:

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

    All properties other than id_product and qty will have the values from the last object seen for that id_product. If you want values from the first seen object, clone a instead of b.