Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the sum of values by key in treemap

There is a stream List<TreeMap<Key, BigDecimal>> how to get TreeMap<Key, BigDecimal>? BigDecimal is summed by key.
List<TreeMap<Key, BigDecimal>> list;
list.stream.flatMap(Collection::stream).collect(….

I don’t know what to do

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

list.stream() gets you a stream of maps.

list.stream().flatMap(m -> m.entrySet().stream()) gets you a stream of map entries – all entries from all maps all bunched up in a single stream.

Now ‘all’ you want to do is to collect these entries back into a single map, applying a merge function to deal with the fact that your stream will contain multiple entries with the same key. The merge function is simply: Add up the BigDecimals.

Let’s first set up a test framework:

List<Map<String, BigDecimal>> input = new ArrayList<>();
var map1 = Map.of("Key1", BigDecimal.ONE, "Key2", new BigDecimal("5.5"));
var map2 = Map.of("Key1", new BigDecimal("1.25"), "Key3", BigDecimal.ONE);
input.add(map1);
input.add(map2);

TreeMap<String, BigDecimal> result = .... /* magic here */;

System.out.println(result);

The magic you want is:

input.stream()
  .flatMap(m -> m.entrySet().stream())
  .collect(Collectors.toMap(
    Map.Entry::getKey,
    Map.Entry::getValue,
    BigDecimal::add,
    TreeMap::new));

BigDecimal::add is the ‘merge’ function. The rest is the standard thing to do when collecting a stream of map entries back into a j.u.Map.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading