Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the TreeMap.putAll() method in Java?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will learn how to use the TreeMap.putAll() method in Java.

Introduction

The TreeMap.putAll() method is used to copy all the mappings from one map to another.

The TreeMap.putAll() method is present in the TreeMap class inside the java.util package.

Syntax

The syntax of the TreeMap.putAll() method is given below:

void putAll(Map m); 

Parameters

The TreeMap.putAll() accepts one parameter:

  • Map: The existing map for copying the mappings to another map.

Return value

The TreeMap.putAll() method does not return any value.

Example

Let’s look at the code below.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();
t1.put(1, "Let's");
t1.put(5, "see");
t1.put(2, "TreeMap class");
t1.put(27, "methods");
t1.put(9, "in java.");
TreeMap<Integer, String> t2 = new TreeMap<Integer, String>();
t2.putAll(t1);
System.out.println("The existing treemap is: " + t1);
System.out.println("The copy of existing treemap created " +
"by putAll() method is: " + t2);
}
}
Using the TreeMap.putAll() method in Java

Explanation

  • Line 1: We import the required package.

  • Line 2: We create a Main class.

  • Line 4: We create a main() function.

  • Line 6: We declare a TreeMap object t1 that consists of keys of type Integer and values of type String.

  • Lines 8 to 12: We use the t1.put() method to insert values in the TreeMap.

  • Line 14: we declare a new TreeMap object t2 that consists of keys of type Integer and values of type String.

  • Line 16: We use the putAll() method to create a copy of the existing map t1.

  • Lines 18 and 19: We display both the existing and new TreeMap associated with a message.

So, in this way, we can use the TreeMap.putAll() method in Java.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring