Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add up BigDecimals contained in a HashMap with Java 8?

What is the easiest way to add to a BigDecimal contained in a HashMap in Java 8?

like image 944
ryvantage Avatar asked Jan 28 '26 03:01

ryvantage


1 Answers

Prior to Java 8, it would be:

public static void main(String[] args) {
    HashMap<String, BigDecimal> bd_map = new HashMap<>();
    bd_map.put("Shirts", BigDecimal.ZERO);
    bd_map.put("Hats", BigDecimal.ZERO);
    bd_map.put("Shoes", BigDecimal.ZERO);

    bd_map.put("Shirts", bd_map.get("Shirts").add(new BigDecimal("5.99")));
    bd_map.put("Shirts", bd_map.get("Shirts").add(new BigDecimal("4.50")));
    bd_map.put("Shoes", bd_map.get("Shoes").add(new BigDecimal("15.99")));
    bd_map.put("Hats", bd_map.get("Hats").add(new BigDecimal("8.00")));
    bd_map.put("Shirts", bd_map.get("Shirts").add(new BigDecimal("8.99")));
    bd_map.put("Shoes", bd_map.get("Shoes").add(new BigDecimal("22.00")));
    bd_map.put("Hats", bd_map.get("Hats").add(new BigDecimal("7.00")));

    System.out.println("Shirts: " + bd_map.get("Shirts"));
    System.out.println("Hats: " + bd_map.get("Hats"));
    System.out.println("Shoes: " + bd_map.get("Shoes"));
}

However, Java 8 makes this much easier and less error-prone with the merge() function:

public static void main(String[] args) {
    HashMap<String, BigDecimal> bd_map = new HashMap<>();

    bd_map.merge("Shirts", new BigDecimal("5.99"), BigDecimal::add);
    bd_map.merge("Shirts", new BigDecimal("4.50"), BigDecimal::add);
    bd_map.merge("Shoes", new BigDecimal("15.99"), BigDecimal::add);
    bd_map.merge("Hats", new BigDecimal("8.00"), BigDecimal::add);
    bd_map.merge("Shirts", new BigDecimal("8.99"), BigDecimal::add);
    bd_map.merge("Shoes", new BigDecimal("22.00"), BigDecimal::add);
    bd_map.merge("Hats", new BigDecimal("7.00"), BigDecimal::add);

    System.out.println("Shirts: " + bd_map.get("Shirts"));
    System.out.println("Hats: " + bd_map.get("Hats"));
    System.out.println("Shoes: " + bd_map.get("Shoes"));
}

Advantages to the Java 8 approach:

  1. No need to initialize the original value (BigDecimal.ZERO)
  2. No need to refer to the old value (HashMap::get) and add it
  3. It's clean
like image 88
ryvantage Avatar answered Jan 30 '26 15:01

ryvantage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!