How to Get the Last Element from LinkedHashSet in Java?


Retrieving the last element from a LinkedHashSet in Java means retrieving its final element present in its collection. Although Java does not come equipped with built-in methods to help retrieve this last item from its LinkedHashSets, multiple effective techniques exist that provide flexibility and convenience, efficiently retrieving this final element without disrupting insertion order - something Java developers must contend with effectively within their apps. By employing such strategies effectively into their software projects they can achieve optimal solutions to meet this requirement efficiently.

LinkedHashSet

LinkedHashSet is an efficient data structure in Java that combines features from HashSet and LinkedList data structures, maintaining unique elements while still preserving their order at insertion time.

Thanks to constant-time operations like insertion, deletion, retrieval and modification it's fast at accessing or changing elements quickly - using hash tables for quick lookup while double linked lists maintain order for maximum accessibility and efficiency.

This structure is ideal when you need to iterate through elements in their order of addition, with predictable iteration order providing optimal conditions. A LinkedHashSet's iteration order also helps in cases when maintaining elements without duplicates while keeping their order of insertion intact.

import java.util.LinkedHashSet;

// ...

LinkedHashSet set = new LinkedHashSet<>();

Approaches

Java allows for several methods for finding the last element from a LinkedHashSet, providing access to its last member. Here are several approaches.

  • Converting to an ArrayList

  • Iterating through the LinkedHashSet

  • Java 8 Stream API

Approach 1: Converting to an ArrayList

An ArrayList in Java is a dynamically allocated, resizable array-based implementation of the List interface that offers flexible and efficient methods for storing and manipulating elements in collections.

As items are added or removed from it, automatically expanding or contracting as elements enter or leave. Internally it maintains an array to store its elements while supporting various methods for adding, removing and accessing them by index.

One way of retrieving the last element from a LinkedHashSet is converting it to an ArrayList via its constructor which accepts Collection as input parameters, then use its get() method to access and extract its last member from it.

Algorithm

  • Create an empty LinkedHashSet.

  • Add elements to the LinkedHashSet.

  • Convert a LinkedHashSet into an ArrayList by creating a new arrayList with your data as its parameter in its constructor.

  • Check the size of an arrayList.

  • If the size exceeds zero:

    • Use the get() method of an ArrayList and pass index(size-1 as its parameter to access its final element.

    • Now is the time for action on our final component.

  • Handling cases where size = 0, signifying an empty LinkedHashSet, should depend upon your specific requirements and considerations.

Program

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class LastElementExample {
   public static void main(String[] args) {
      LinkedHashSet<String> linkedSet = new LinkedHashSet<>();
      linkedSet.add("Apple");
      linkedSet.add("Banana");
      linkedSet.add("Orange");
      linkedSet.add("Mango");

      ArrayList<String> arrayList = new ArrayList<>(linkedSet);
      String lastElement = arrayList.get(arrayList.size() - 1);

      System.out.println("Last element: " + lastElement);
   }
}

Output

Last element: Mango

Approach 2: Iterating through the LinkedHashSet

Java allows users to iterate through a LinkedHashSet by iteration in several steps, starting from creating an empty LinkedHashSet to adding elements. After adding elements, initiate iteration using either an iterator or for-each loop - iterators may access their object using iterator() from within the LinkedHashSet while for-each loops can check if more are present using hasNext() method.

Each iteration, use the next() method to access and retrieve the current element and update a variable with that element's value; by the end of iterations, this variable should contain its final element and you can utilize this variable accordingly for future operations or processing needs.

Algorithm

  • Create an empty LinkedHashSet.

  • Add elements to the LinkedHashSet.

  • Use an iterator or for-each loop to traverse through the LinkedHashSet:

    • Create an iterator using the iterator() method of LinkedHashSet.

    • Use a while loop and hasNext() method to identify whether there are more elements.

    • Use the next() method within a loop to retrieve the current element.

  • Update the current element's value into an appropriate variable during every iteration.

  • Once iteration completes, the variable will contain its last element.

Program

import java.util.Iterator;
import java.util.LinkedHashSet;

public class LastElementExample {
   public static void main(String[] args) {
      LinkedHashSet<Integer> linkedSet = new LinkedHashSet<>();
      linkedSet.add(10);
      linkedSet.add(20);
      linkedSet.add(30);
      linkedSet.add(40);

      Integer lastElement = null;
      Iterator<Integer> iterator = linkedSet.iterator();
      while (iterator.hasNext()) {
         lastElement = iterator.next();
      }

      System.out.println("Last element: " + lastElement);
   }
}

Output

Last element: 40

Approach 3: Java 8 Stream API

To obtain the last element from a LinkedHashSet using Java 8 Stream API, follow these steps. Create an empty LinkedHashSet, add elements, convert to a stream using stream() method, reduce() terminal operation with lambda function returning identity value can reduce stream to single element; in this instance the lambda always returns second parameter representing current element.

Finally use orElse() method when empty LinkedHashSet is encountered and assign default value such as null for orElse() case which then contains last element from that LinkedHashSet for further processing operations or processing purposes.

Algorithm

  • Create an empty LinkedHashSet.

  • Add elements to the LinkedHashSet.

  • Convert LinkedHashSet into Stream using stream() method.

  • Utilizing the reduce() terminal operation requires two parameters - an endless lambda function which always returns its second parameter as its argument and the identity value for BinaryOperators.

  • Reduce will effectively convert an array to an element in its entirety - for instance, becoming part of LinkedHashSet as its final element.

Program

import java.util.LinkedHashSet;
import java.util.Optional;

public class LastElementExample {
   public static void main(String[] args) {
      LinkedHashSet<String> linkedSet = new LinkedHashSet<>();
      linkedSet.add("Carrot");
      linkedSet.add("Broccoli");
      linkedSet.add("Spinach");
      linkedSet.add("Tomato");

      Optional<String> lastElement = linkedSet.stream().reduce((first, second) -> second);

      if (lastElement.isPresent()) {
         System.out.println("Last vegetable: " + lastElement.get());
      } else {
         System.out.println("LinkedHashSet is empty.");
      }
   }
}

Output

Last vegetable: Tomato

Conclusion

This tutorial highlighted effective approaches for retrieving the last element from a LinkedHashSet in Java, without resorting to dedicated methods for this task. By converting their linkedHashSet into an ArrayList and accessing its index number as its last element index number. Searching a LinkedHashSet with tracking the last element encountered enables retrieval.

Furthermore, using Java 8's Stream API with its reduce operation provides an elegant solution. These methods offer flexibility, efficiency and maintain the insertion order of a LinkedHashSet. By either converting to an ArrayList, iterating or making use of Java's Stream API API, Java developers can confidently extract last element from a LinkedHashSet in various situations.

Updated on: 25-Jul-2023

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements