Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two TreeMaps while skipping the first entry in Java

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());
}

)

like image 227
Saleh Pirouzi Avatar asked Jun 30 '26 23:06

Saleh Pirouzi


1 Answers

You can use tailMap:

TreeMap<foo, bar> result = new TreeMap<>(map1);
result.putAll (map2.tailMap (map2.keySet().iterator().next(), false));

EDIT: You don't need to find the second key. You can run tailMap with inclusive == false, and pass to it the first key, which will be excluded.

like image 66
Eran Avatar answered Jul 02 '26 11:07

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!