Java Puzzle – Predict TreeMap put() Output

1. Question

Go through the given Java program. The program adds key-value pairs in the TreeMap which already has a few key-value pairs.

Predict the output.

Map<String, String> 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") );

2. Answer

The program outputs:

test value 3

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

3. Reasoning

If we look at Map.put() operation, it returns the value if the key-value is already present in the Map. Or we can say when the put() operation updates an existing Map entry.

After adding the key “test key 3”, when we add it a second time, it returns the value “test value 3”.

But, when we add “test key 4” which is the first-time entry, it is not present in Map, so the map returns its value as null.

Happy Learning !!

Sourcecode on Github

1 Comment
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.