Merging two TreeMaps while skipping the first entry in Java

Viewed 329

I have two TreeMaps which I want to merge:

TreeMap<foo, bar> map1 = {key1=value1, key2=value2};
TreeMap<foo, bar> map2 = {key1=value6, key3=value3, key4=value4, key5=value5};

I want to merge these maps into a single one but I want to skip the first entry of second map, so I will have something like this:

TreeMap<foo, bar> result = {key1=value1, key2=value2, key3=value3, key4=value4, key5=value5};

However, I cannot call map2.remove(map2.firstKey()) or even map2.remove(key1) because equals does not work fine on foo.

Is there a good way to do this?

(At the moment I am doing this which works fine, but I am not quite happy with it and I do not think it is the best way:

TreeMap<foo, bar> result = new TreeMap<>();
result.putAll(map1);

for (Map.Entry<foo, bar> entry : Iterables.skip(map2.entrySet(), 1) ) {
  result.put(entry.getKey(), entry.getValue());
}

)

3 Answers
Related