Programa Java para comprobar si el TreeMap está vacío

TreeMap en Java se utiliza para implementar la interfaz Map y NavigableMap junto con la clase AbstractMap. El mapa se ordena según el orden natural de sus claves, o mediante un comparador proporcionado en el momento de la creación del mapa, según el constructor que se utilice.

Enfoques: 

  1. Usando el método i sEmpty()
  2. Usando el método de tamaño()

Método 1: Usar el método i sEmpty()

El método java.util.TreeMap.isEmpty() de la clase TreeMap se usa para verificar el vacío del TreeMap.

Sintaxis:

TreeMap.isEmpty()

Parámetros: El método no toma ningún parámetro.

Valor devuelto: el método devuelve un booleano verdadero si el TreeMap está vacío; de lo contrario, es falso. Por lo tanto, devolverá falso si hay al menos una asignación de clave-valor en el objeto TreeMap si no es verdadero.

Ejemplo:

Java

// Java Program to Check if the TreeMap is Empty
// using the isEmpty() method
 
// Importing TreeMap class of
// java.util package
import java.util.TreeMap;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Create an empty TreeMap
        TreeMap<Integer, String> tmap
            = new TreeMap<Integer, String>();
 
        // Check TreeMap is empty or not
        boolean isEmpty = tmap.isEmpty();
        System.out.println("Is tmap empty :  " + isEmpty);
 
        // Mapping string values to int keys
        tmap.put(1, "Geeks");
        tmap.put(2, "For");
        tmap.put(3, "skeeG");
 
        // Displaying the TreeMap
        System.out.println("The Mappings are: " + tmap);
 
        // Checking again TreeMap is empty or not
        isEmpty = tmap.isEmpty();
 
        // Display boolean output again
        // to show isEmpty() method functionality
        System.out.println("Is tmap empty : " + isEmpty);
      
    }
}
Producción

Is tmap empty :  true
The Mappings are: {1=One, 2=Two}
Is tmap empty : false

Método 2: Usar el método  size()

El método java.util.TreeMap.size() de la clase TreeMap se usa para verificar el vacío del TreeMap comparando el tamaño con 0. El método devuelve True si TreeMap está vacío, de lo contrario, false.

Sintaxis:

(TreeMap.size() == 0) ;

Parámetros: El método no toma ningún parámetro.

Valor devuelto: el método devuelve el booleano True si el TreeMap está vacío, de lo contrario, false.

Ejemplo:

Java

// Java Program to Check if the TreeMap is Empty
// and illustrating the size() method
 
// Importing TreeMap class of
// java.util package
import java.util.TreeMap;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Create an empty TreeMap
        TreeMap<Integer, String> tmap
            = new TreeMap<Integer, String>();
 
        // Check TreeMap is empty or not
        // Using size() method
        System.out.println("Is map empty : "
                           + (tmap.size() == 0));
 
        // Mapping string values to int keys
        // Custom inputs mapping
        tmap.put(1, "One");
        tmap.put(2, "Two");
 
        // Displaying the TreeMap
        System.out.println("The Mappings are: " + tmap);
 
        // Display boolean output again
        // to show size() method functionality
        System.out.println("Is map empty : "
                           + (tmap.size() == 0));
    }
}
Producción

Is map empty : true
The Mappings are: {1=One, 2=Two}
Is map empty : false

Nota: La misma operación se puede realizar con cualquier tipo de Mapping con variación y una combinación de diferentes tipos de datos.

Publicación traducida automáticamente

Artículo escrito por incredeble y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *