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
>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.