Métodos especiales de Java TreeSet

TreeSet es una de las implementaciones más importantes de la interfaz SortedSet en Java que utiliza un árbol para el almacenamiento. TreeSet implementa una interfaz NavigableSet al heredar la clase AbstractSet . Esto significa que los elementos almacenados en un TreeSet están ordenados, es decir, en orden ascendente. Debido a esta característica de TreeSet, proporciona ciertos métodos sorprendentes de la interfaz NavigableSet además de los que proporciona tradicionalmente la interfaz Collection.

Nota: dado que TreeSet es la implementación de Set, no permite la duplicación de elementos.

Algunos de los métodos específicos proporcionados por TreeSet son los siguientes:

  1. Método Floor()
  2. método inferior()
  3. método techo()
  4. método superior()
  5. Método subconjunto()
  6. Método headSet()
  7. método tailSet()

Ahora analicemos todos los métodos junto con su implementación, que es la siguiente

Método 1: Método Floor ()

Este método devuelve el mayor elemento del conjunto menor o igual que el elemento dado, o nulo si no existe tal elemento.

Argumentos: se debe buscar un número menor o igual que el valor

Sintaxis:

treeSetObject.floor(argument) ;

Ejemplo:

Java

// Java Program to demonstrate Floor Method in TreeSet
 
// Importing input output classes
import java.io.*;
// Importing TreeSet and Set classes from java.util package
import java.util.Set;
import java.util.TreeSet;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeSet of Integer type
        // Initializing object with integer values using
        // Set.of() method
        TreeSet<Integer> treeSet
            = new TreeSet<>(Set.of(12, 98, 54, 37, 68));
 
        // Print and display elements in object
        System.out.println("Tree set = " + treeSet);
 
        // Case 1
 
        // Using floor() method over treeSet elements but
        // note floor() method is inclusive of the limit
        // Hence maximum element is returned
        System.out.println("floor(60) = "
                           + treeSet.floor(60));
 
        // Case 2
 
        // Using floor() method over treeSet elements,
        // therefore output of the below line will be the
        // number itself
        System.out.println("floor(54) = "
                           + treeSet.floor(54));
    }
}
Producción

Tree set = [12, 37, 54, 68, 98]
floor(60) = 54
floor(54) = 54

Método 2: método inferior ()

Este método devuelve el mayor elemento de este conjunto estrictamente menor que el elemento dado, o nulo si no existe tal elemento.

Argumento: Número cuyo valor menor que se necesita encontrar.

Sintaxis: 

treeSetObject.lower(argument) ;

Ejemplo:

Java

// Java Program to demonstrate Lower Method in TreeSet
 
// Importing input output classes
import java.io.*;
// Importing TreeSet and Set classes from java.util package
import java.util.Set;
import java.util.TreeSet;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeSet of Integer type
        // Initializing object with integer values using
        // Set.of() method
        TreeSet<Integer> treeSet
            = new TreeSet<>(Set.of(12, 98, 54, 37, 68));
 
        // Print and display elements in object
        System.out.println(treeSet);
 
        // Case 1
        // Using lower() method over treeSet elements where
        // argument passed is greater then max element in
        // TreeSet therefore returning max element itself
        System.out.println("lower(90) = "
                           + treeSet.lower(90));
 
        // Case 2
        // Using lower() method over treeSet elements where
        // argument passed is not greater then max element
        // in TreeSet therefore returning element lesser
        // than that passed as an argument
        System.out.println("lower(68) = "
                           + treeSet.lower(68));
 
        // Also note that lower() method is exclusive of the
        // limit
    }
}
Producción

[12, 37, 54, 68, 98]
lower(90) = 68
lower(68) = 54

Método 3: Método techo ()

Este método devuelve el elemento mínimo de este conjunto mayor o igual que el elemento dado, o nulo si no existe tal elemento.

Argumento: Número cuyo valor menor o igual se necesita encontrar.

Sintaxis: 

treeSetObject.lower(argument) ;

Ejemplo:

Java

// Java Program to demonstrate Ceiling Method in TreeSet
// Importing input output classes
import java.io.*;
// Importing TreeSet and Set classes from java.util package
import java.util.Set;
import java.util.TreeSet;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeSet of Integer type
        // Initializing object with integer values using
        // Set.of() method
        TreeSet<Integer> treeSet
            = new TreeSet<>(Set.of(12, 98, 54, 37, 68));
 
        // Print and display elements in object
        System.out.println("tree set = " + treeSet);
 
        // Using ceiling() method.
        System.out.println("ceiling(50) = "
                           + treeSet.ceiling(50));
 
        // Note that ceiling method is inclusive of the
        // limit. Therefore,output of the below line will be
        // the same number.
        System.out.println("ceiling(68) = "
                           + treeSet.ceiling(68));
 
        // Verification for null
        System.out.println("ceiling(100) = "
                           + treeSet.ceiling(100));
    }
}
Producción

tree set = [12, 37, 54, 68, 98]
ceiling(50) = 54
ceiling(68) = 68
ceiling(100) = null

Método 4: método superior  () 

Este método devuelve el elemento mínimo de este conjunto estrictamente mayor que el elemento dado, o nulo si no existe tal elemento.

Argumento: El número cuyo valor menor que necesita ser encontrado.

Sintaxis:

treeSetObject.lower(argument) ;

Ejemplo:

Java

// Java Program to demonstrate Higher Method of TreeSet
 
// Importing input output classes
import java.io.*;
// Importing Set and TreeSet classes from java.util package
import java.util.Set;
import java.util.TreeSet;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeSet of Integer type
        // Initializing object with integer values using
        // Set.of() method
        TreeSet<Integer> treeSet
            = new TreeSet<>(Set.of(12, 98, 54, 37, 68));
 
        // Print and display elements in object
        System.out.println("tree set = " + treeSet);
 
        // Using higher() method
 
        // Case 1
        System.out.println("higher(50) = "
                           + treeSet.higher(50));
 
        // Case 2
        // Note that higher method is exclusive of the limit
        // causing
        //  output be the number greater than the number
        //  passed
        System.out.println("higher(68) = "
                           + treeSet.higher(68));
 
        // Case 3
        // Verification for null
        System.out.println("higher(98) = "
                           + treeSet.higher(100));
    }
}
Producción

tree set = [12, 37, 54, 68, 98]
higher(50) = 54
higher(68) = 98
higher(98) = null

Método 5: Método subSet ()

Este método devolverá elementos que van desde ‘ fromElement ‘ hasta ‘ toElement ‘.

Nota : ‘fromElement’ es inclusivo y ‘toElement’ es exclusivo.

Sintaxis:

treeSetObject.subSet(fromElement, toElement);
// where fromElement is the lower limit (inclusive) and 
// toElement is the upper limit (exclusive) 
// of the set containing values between these limits

Ejemplo:

Java

// Java Program to demonstrate subset Method in TreeSet
 
// Importing input output classes
import java.io.*;
// Importing Set and TreeSet classes from java.util package
import java.util.Set;
import java.util.TreeSet;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeSet of Integer type
        // Initializing object with integer values using
        // Set.of() method
        TreeSet<Integer> treeSet
            = new TreeSet<>(Set.of(12, 98, 54, 37, 68));
 
        // Print and display elements in object
        System.out.println("tree set = " + treeSet);
 
        // Using subSet() method
 
        // Case 1
        System.out.println(
            "Elements between 54 and 98 are : "
            + treeSet.subSet(54, 98));
 
        // Case 2
        // If we want to include the upper limit
        System.out.println(
            "Elements between 54 and 98 including both the limits : "
            + treeSet.subSet(54, true, 98, true));
 
        // Case 3
        // If we want to exclude the lower limit
        System.out.println(
            "Elements between 54 (exclusive) and 98 (inclusive) : "
            + treeSet.subSet(54, false, 98, true));
 
        // Case 4
        // If we want to exclude both the limits
        System.out.println(
            "Elements between 54 (exclusive) and 98 (exclusive) : "
            + treeSet.subSet(54, false, 98, false));
    }
}
Producción

tree set = [12, 37, 54, 68, 98]
Elements between 54 and 98 are : [54, 68]
Elements between 54 and 98 including both the limits : [54, 68, 98]
Elements between 54 (exclusive) and 98 (inclusive) : [68, 98]
Elements between 54 (exclusive) and 98 (exclusive) : [68]

Método 6: Método headSet ()

Este método devolverá elementos de TreeSet que son menores que el elemento especificado.

Sintaxis:

treeSetObject.headSet(upToNumber) ;

Nota:upToNumber ‘ es el límite superior de los números a encontrar (exclusivo)

Ejemplo:

Java

// Java Program to demonstrate headSet Method in TreeSet
 
// Importing input output classes
import java.io.*;
// Importing Set and TreeSet classes from java.util package
import java.util.Set;
import java.util.TreeSet;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeSet of Integer type
        // Initializing object with integer values using
        // Set.of() method
        TreeSet<Integer> treeSet
            = new TreeSet<>(Set.of(12, 98, 54, 37, 68));
 
        // Print and display elements in object
        System.out.println("tree set = " + treeSet);
 
        // Implementing headSet() method via TreeSet object
 
        // Case 1
        System.out.println("Elements upto 90 : "
                           + treeSet.headSet(90));
 
        // Case 2
        // The function limit is exclusive of the argument
        // passed
        System.out.println("Elements upto 68 : "
                           + treeSet.headSet(68));
 
        // Case 3
        // If we want to include the number passed, then
        System.out.println("Elements upto 68 (inclusive) : "
                           + treeSet.headSet(68, true));
    }
}
Producción

tree set = [12, 37, 54, 68, 98]
Elements upto 90 : [12, 37, 54, 68]
Elements upto 68 : [12, 37, 54]
Elements upto 68 (inclusive) : [12, 37, 54, 68]

Método 7: 

Este método devolverá elementos de TreeSet que son mayores o iguales que el elemento especificado. 

Sintaxis:

treeSetObject.tailSet(aboveThisNumber) ;

Nota:overThisNumber’ es el límite inferior de los números que se encontrarán (inclusive).

Ejemplo:

Java

// Java Program to demonstrate tailSet Method in TreeSet
 
// Importing input output classes
import java.io.*;
import java.util.Set;
import java.util.TreeSet;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeSet of Integer type
        // Initializing object with integer values using
        // Set.of() method
        TreeSet<Integer> treeSet
            = new TreeSet<>(Set.of(12, 98, 54, 37, 68));
 
        // Print and display elements in object
        System.out.println("tree set = " + treeSet);
 
        // Implementing tailSet()
 
        // Case 1
        System.out.println("Elements above 50 : "
                           + treeSet.tailSet(50));
 
        // Case 2
        // The function limit is inclusive of the argument
        // passed
        System.out.println("Elements above 54 : "
                           + treeSet.tailSet(54));
 
        // Case 3
        // If we want to exclude the number passed
        System.out.println(
            "Elements above 54 (exclusive) : "
            + treeSet.tailSet(54, false));
    }
}
Producción

tree set = [12, 37, 54, 68, 98]
Elements above 50 : [54, 68, 98]
Elements above 54 : [54, 68, 98]
Elements above 54 (exclusive) : [68, 98]

Publicación traducida automáticamente

Artículo escrito por ankitsinghrajput 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 *