Java puzzle – TreeMap put operation

Puzzle : I have given a below map with the following below options,

Map map = new TreeMap();
map.put("test key 1", "test value 1");
map.put("test key 2", "test value 2");
map.put("test key 3", "test value 3");
 
System.out.println(map.put("test key 3", "test value 3"));
System.out.println(map.put("test key 4", "test value 4"));

Option A) System.out.println(map.put(“test key 3”, “test value 3”));
Answer) This prints the output as = test value 3

Option B) System.out.println(map.put(“test key 4”, “test value 4”));
Answer) This prints the output as = null;

Can anyone please explain why option b is giving us such a behavior?

Also when I print the map after the Option B sysout statement, I have the test key 4 present in it?

Solution : If you look at Map.put() operation, it returns the value if key is already present in map.

After adding key “test key 3”, when again try to add it, it returns the value “test value 3”.

When you add “test key 4” first time, it is no present in map, so map return’s it’s value is null.

Next time when you store “test key 4”, this time entry is already present so value is returned as “test value 4”

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Java puzzle – TreeMap put operation”

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.