Programa Java para obtener elementos por índice de LinkedHashSet

LinkedHashSet es una clase predefinida en Java que es similar a HashSet. A diferencia de HashSet, en LinkedHashSet se conserva el orden de inserción. Para obtener un elemento por índice de LinkedHashSet en Java, tenemos varias formas.

Ilustración:

Input      : 2, 3, 4, 2, 7;
Processing : index = 4;
Output     : Element at index 4 is : 7

Métodos:

  1. Un enfoque ingenuo usando el método de conteo de iteraciones
  2. Convertir LinkedHashSet a Array
  3. Convertir LinkedHashSet en lista

Método 1: enfoque ingenuo que utiliza el método de iteración para el recuento de índices y para obtener el elemento en el índice dado.

Algoritmo

  1. Use el iterador para atravesar nuestro LinkedHashSet.
  2. Iniciar puntero de índice índice actual = 0
  3. Comience la iteración usando un ciclo while y si el índice actual se vuelve igual al índice dado, imprima el elemento.
Pseudo Code: 
Iterator<Integer> it = LHS.iterator();
while(it.hasNext()) {}

Implementación:

Ejemplo 1

Java

// Java Program to Get Elements by Index from LinkedHashSet
// Using iteration count method
 
// Importing generic java libraries
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
 
    {
        // Adding elements to LinkedHashSet
        // Custom inputs
        LinkedHashSet<Integer> LHS = new LinkedHashSet<>();
        LHS.add(2);
        LHS.add(3);
        LHS.add(4);
        LHS.add(2);
        LHS.add(7);
 
        // Custom index chosen to get the element
        // present at that index
        int index = 4;
 
        Iterator<Integer> it = LHS.iterator();
 
        // Assigning initial values
        int currIndex = 0;
        Integer CurrentElement = null;
 
        // Condition check using hasNext(), whick
        // returns true if another token as input
        while (it.hasNext()) {
 
            // next element using iterator is
            // assigned to variable
            CurrentElement = it.next();
 
            // Variable condition check
            if (currIndex == index - 1) {
                System.out.println("Element at index "
                                   + index + " is : "
                                   + CurrentElement);
                break;
            }
 
            // If condition fails, so
            // Incrementing current index
            currIndex++;
        }
    }
}
Producción

Element at index 4 is : 7

Complejidad de tiempo: O(n)

Método 2: LinkedHashSet se convierte en Array mediante el cual se puede acceder al elemento en el índice dado.

Algoritmo: 

  1. Convierta LinkedHashSet dado a Array usando el método toArray() .
  2. Accediendo al elemento en el índice dado en la array.
Pseudo Code:
Integer[] LHSArray = new Integer[LHS.size()];
LHSArray = LHS.toArray(LHSArray);

Ejemplo  

Java

// Java Program to Get Elements by Index from LinkedHashSet
// By converting LinkedHashSet to Array
 
// Importing generic java libraries
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a LinkedHashSet
        LinkedHashSet<Integer> LHS = new LinkedHashSet<>();
 
        // Adding elements() to LinkedHashSet
        LHS.add(2);
        LHS.add(3);
        LHS.add(4);
        LHS.add(2);
        LHS.add(7);
 
        // Custom index chosen from LinkedHashSet
        int index = 4;
 
        // Converting LnkedHashMap to Array
        Integer[] LHSArray = new Integer[LHS.size()];
        LHSArray = LHS.toArray(LHSArray);
 
        // Printing desired value at index in array,
        // chosen above index from LinkedHashap
        System.out.println("Element at index " + index
                           + " is : "
                           + LHSArray[index - 1]);
    }
}
Producción

Element at index 4 is : 7

Complejidad de tiempo: O(1)

Método 3: LinkedHashSet se convertirá en Lista para obtener el elemento deseado en el índice dado.

Algoritmo 

  1. Convierta nuestro LinkedHashMap a List como ArrayList.
  2. Usando el método get() para obtener un elemento en un índice dado.
Pseudo Code :List<Integer> LHSList =new ArrayList<>(LHS);
              where LHS is name of our LinkedHashSet

Implementación

Java

// Java Program to Get Elements by Index from LinkedHashSet
// By converting LinkedHashSet to List
 
// Importing java generic libraries
import java.util.*;
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a LinkedHashSet
        LinkedHashSet<Integer> LHS = new LinkedHashSet<>();
 
        // Adding elements to LinkedHashSet
        LHS.add(2);
        LHS.add(3);
        LHS.add(4);
        LHS.add(2);
        LHS.add(7);
 
        // Custom index chosen to retrieve value
        int index = 4;
 
        // Converting LinkedHashSet to List
        Iterator<Integer> it = LHS.iterator();
 
        // Assigning initial values
        int currIndex = 0;
        Integer CurrentElement = null;
 
        // Condition check using hasNext(), whick
        // returns true if another token as input
        while (it.hasNext()) {
            CurrentElement = it.next();
 
            if (currIndex == index - 1) {
 
                // Printing desired value at index in array,
                // chosen above index from LinkedHashap
                System.out.println("Element at index "
                                   + index + " is : "
                                   + CurrentElement);
                break;
            }
 
            // Incrementing the current index
            currIndex++;
        }
    }
}
Producción

Element at index 4 is : 7

Publicación traducida automáticamente

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