Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mergeMaps doesn't work when first map has no elements?

I try to merge two maps

      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 current has 0 elements, the lambda is not executed.

Isn't merge should do union in case no merge is possible?

I want:

map1{} ; map2{<a,<a1>>} returns map3{<a,<a1>>}

map1{<a,<b1>>} ; map2{<a,<a1>>} returns map3{<a,<a1, b1>>}
like image 681
Elad Benda Avatar asked Nov 09 '22 01:11

Elad Benda


1 Answers

If you call forEach on an empty collection, there is obviously nothing on which to execute the lambda.

If HashMap.merge is the way you want to merge the lists, you could swap the maps round in the case that the first is empty:

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

However, that will add elements to other, rather than current.

Alternatively, you can just putAll everything into the first map:

if (current.isEmpty()) {
  current.putAll(other);
}
like image 163
Andy Turner Avatar answered Nov 14 '22 23:11

Andy Turner