Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

treemap
size
java
communitycreator

What is the TreeMap.size() 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.size() method in Java.

Introduction

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

The TreeMap.size() method is used to obtain the number of key-value pairs present in the map.

Syntax

The syntax of the TreeMap.size() method is shown below:

TreeMap.size();

Parameters

The TreeMap.size() method does not accept any parameters.

Return value

The TreeMap.size() method returns the number of key-value pairs present in the TreeMap.

Working example

Let’s have a look at the code:

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> s = new TreeMap<Integer,String>();
s.put(2,"Learn");
s.put(12,"in-demand");
s.put(31,"tech");
s.put(18,"skills");
s.put(25,"on");
s.put(36,"Educative.io");
System.out.println("TreeMap mappings are: "+ s);
System.out.println("The size of the TreeMap is " + s.size());
}
}
Use TreeMap.size() method in Java

Explanation

  • In line 1, we imported the required package.

  • In line 2, we made a Main class.

  • In line 4, we made a main() function.

  • In line 6, we declared a TreeMap consisting of keys of type Integer and values of type String.

  • From lines 8 to 13, we inserted values in the TreeMap by using the TreeMap.put() method.

  • In line 15, we displayed the mappings of the present in the TreeMap.

  • In line 17, we used TreeMap.size() method to obtain the number of key-value pairs present in the TreeMap.

So, this is the way to use the TreeMap.size() method in Java.

RELATED TAGS

treemap
size
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