Friday, October 28, 2022

Java Map size() With Examples

If you want to know how many key-value pair are there in a Map you can use size() method which returns the number of key-value mappings in the map.

Syntax of the size() method is

int size()

Method doesn't take any parameters.

Method returns an int value denoting the number of key-value mappings in the map

size() method Java example

Here we have a HashMap with some key, value pair added. Using size() method we'll get the current size of the map.

import java.util.HashMap;
import java.util.Map;

public class SizeMapDemo {
  public static void main(String[] args) {
    Map<String, String> cityMap = new HashMap<String, String>();
    // Adding elements
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Beijing");
    cityMap.put("5", "Berlin");
    int sizeOfMap = cityMap.size();
    System.out.println("Number of entries in the Map: " + sizeOfMap);


Number of entries in the Map: 5

That's all for this topic Java Map size() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. removeIf() Method in Java Collection With Examples
  2. Java Map putIfAbsent() With Examples
  3. Java Map replace() With Examples
  4. Difference Between ArrayList And LinkedList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. CopyOnWriteArrayList in Java With Examples
  3. Type Wrapper Classes in Java
  4. Why Class Name And File Name Should be Same in Java
  5. Convert String to Char Array in Java
  6. Python First Program - Hello World
  7. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  8. What is SafeMode in Hadoop

No comments:

Post a Comment