Bag with non-integer number Map <Object, BigDecimal>

I need to match objects with their counts, like with bag or multi-set , but with a BigDecimal number, not an integer.

So, for example, I could add 2.3 kg of sugar, 4.5 kg of salt and another 1.4 kg of sugar. Then, if I I get sugar, it will return 3.7. If I get salt, it will return 4.5.

I can write one quite easily, but can there be an existing implementation that I can use? and what is called this data structure?

+5
source share
2 answers

You can simply use the new Map api merge introduced in java-8 :

 Map<String, BigDecimal> counts = new HashMap<>(); counts.merge("sugar", BigDecimal.valueOf(2.3), BigDecimal::add); counts.merge("salt", BigDecimal.valueOf(4.5), BigDecimal::add); counts.merge("pepper", BigDecimal.valueOf(1.8), BigDecimal::add); counts.merge("sugar", BigDecimal.valueOf(1.4), BigDecimal::add); System.out.println(counts); // {pepper=1.8, salt=4.5, sugar=3.7} 
+3
source

How about a custom hashmap? Can't think of a simpler solution.

In Java 7:

 class Bag extends HashMap<Object, BigDecimal> { public void add(Object key, BigDecimal value){ if (containsKey(key)) value = get(key).add(value); put(key, value); } } 

Or, in Java 8:

 class Bag extends HashMap<Object, BigDecimal> { public void add(Object key, BigDecimal value){ merge(key, value, BigDecimal::add); } } 

Using:

 Bag bag = new Bag(); bag.add("Sugar", BigDecimal.valueOf(2.3)); bag.add("Salt", BigDecimal.valueOf(4.5)); bag.add("Sugar", BigDecimal.valueOf(1.4)); System.out.println(bag.get("Sugar")); // Prints 3.7 
+1
source

Source: https://habr.com/ru/post/1264527/


All Articles