I have two TreeMap
like,
fisrtMap{
"2022": "11",
"2023": "22"
}
secondMap{
"2022": "33"
}
I want to make the firstMap
like,
fisrtMap{
"2022": "11"
}
I mean, I need to remove uncommon keys from maps.
Set
of keys from both Map
objectsThe solution applies to any modifiable Map
class, not just the TreeMap
class you mention.
As commented by Pshemo, your can do this by way of 👉 a set of keys of each map.
First set up some sample data. We make a modifiable map x
by using Map.of
literals syntax for convenience.
Map < String, String > x =
new HashMap <>(
Map.of(
"2022" , "11" ,
"2023" , "22"
)
);
Map < String, String > y =
Map.of(
"2022" , "33"
);
Get a view on the keys of map x
as a set. Then remove any entries in that map where the key is not present in a second set, a set of keys from the second map.
x.keySet().retainAll( y.keySet() );
That call to Map::keySet
returns a Set
view of the keys contained in the map. That set is special, in that it is connected to the map from which it came. To quote the Javadoc:
The set supports element removal, which removes the corresponding mapping from the map
Dump to console the before and after state of our map x
.
System.out.println( "x = " + x );
x.keySet().retainAll( y.keySet() );
System.out.println( "x = " + x );
See this code run live at Ideone.com.
x = {2023=22, 2022=11}
x = {2022=11}
By the way, if that first part of your data is meant to be a calendar year, you could make use of the java.time.Year
class.