MergeMaps not working when the first map has no items?

I'm trying to combine two cards

private void mergeMaps(HashMap<String, FailureExample> current, HashMap<String, FailureExample> other) { current.forEach((k, v) -> other.merge(k, v, (v1, v2) -> { FailureExample answer = new FailureExample(); addFromListWithSizeLimit(v1, answer); addFromListWithSizeLimit(v2, answer); // answer.requests.addAll(v1.requests); // answer.requests.addAll(v2.requests); return answer; })); } 

but when the current has 0 elements, lambda is not executed.

Does merging happen if merging is not possible?

I want to:

 map1{} ; map2{<a,<a1>>} returns map3{<a,<a1>>} map1{<a,<b1>>} ; map2{<a,<a1>>} returns map3{<a,<a1, b1>>} 
+5
source share
1 answer

If you call forEach in an empty collection, obviously nothing is needed to execute the lambda.

If HashMap.merge is the way you want to merge lists, you can swap cards around if the first one is empty:

 if (current.isEmpty()) { HashMap<String, FailureExample> tmp = current; current = other; other = tmp; } 

However, this will add elements to other , not current .

Alternatively, you can simply putAll everything in the first card:

 if (current.isEmpty()) { current.putAll(other); } 
+1
source

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


All Articles