Java Program to Get First or Last Elements from HashSet


In Java, HashSet is a class which implements Set Interface. HashSet is a collection of unique elements which doesn’t store or allow us to store duplicate elements. In this section, we will be discussing about different approaches in java to find the first element and last element of a hashSet using Java programming Language.

The HashSet class in java is implemented using a hash table. It uses hash code to retrieve data quickly from the table.in HashSet, the order of elements is not preserved i.e., it doesn’t store the elements in the order in which we add elements to the set. We can perform operations like adding, deleting, searching on the elements. As elements are not stored in a particular order hence they are unordered elements. When we retrieve the elements from hashset we cannot predict the order of the elements in which they will be retrieved.

Basic Operations on HashSet

Here, we will discuss regarding the basic operations that we can perform on HashSet using in built methods provided by Java HashSet Class.

add() − This method helps to add elements to the HashSet.It accepts a parameter basically the type of elements stored in the HashSet.

hashSetObject.add(element)

remove() − This method helps to remove elements from the HashSet. The element passed to this method is removed from the hashSet.

set.remove("b"); // removes "b" from the set

clear() − This method helps to clear all elements from the HashSet.

set.clear(); // removes all elements from set

contains() − This method helps to check whether an element which is passed as a parameter is present in the HashSet. It returns boolean value. If the element is present it returns true else returns false.

boolean val = set.contains(‘b’); // checks ‘b’ is present and returns boolean value.

isEmpty() − This method helps to check whether the HashedSet is empty or not. It returns boolean value. If the hashset is empty is it returns true else returns false.

boolean val = set.isEmpty(); // checks hashSet conatians elements or not

Syntax

Creating an instance of HashSet − The HashSet() constructor can be used to create a HashSet object.

HashSet<datatype> obj= new HashSet();
Example : 
HashSet<String>  hm  = new HashSet() ; // creates a hashSet with string type.

Creating ArrayList − The ArrayList() constructor can be used to create a ArrayList object. It is used to store homogenous elements. It allows duplicates.

ArrayList<datatype> obj = new ArrayList<>();
Example :
ArrayList<String> ls  = newArrayList() ; // creates a ArrayList with string type.

iterator() − It is an object which helps us to iterate over the elements in the collection and returns the values using hasNext() method on this object.

Iterator<datatype> iteratorobjectname =CollectionObject.iterator()

hasNext() − This method is used check whether next element is present in the collection. It is provided by the Iterator Interface in java. It is called on iterator Object.

iteraratorObject.hasNext()

next() − This method helps us to return the next element present in the collection.It is provided by the Iterator Interface in java. It is called on iterator Object.

iteraratorObject.next()

toArray() − This method is used to convert a collection into an array.It returns an array of elements.

collectionobject.toArray()

Now, we will be discussing in detail through java codes how to find the first or last elements from a HashSet.

Approach 1: Using iterator() method

In this approach, we first create a HashSet object and then add a few elements to HashSet using add() method. We create the iterator object on the set object and use next() method to get the first element in the set and store value in ‘first’ variable and we then initialise ‘last’ variable with zero and iterate over the set of elements using foreach loop and store the element in ‘last’ variable and at last print the value of ‘first’ and ‘last’ variables.

Algorithm

  • Create a HashSet instance and add elements to the set using the add() method.

  • Create an iterator instance and retrieve the first element using next() method.

  • Using the for loop, iterate through the set and get the last element.

  • Print the first and last elements.

Example

In this example, we will use the iterator() method and find the first and last elements in HashSet.

import java.util.*;

public class Main {
   public static void main(String[] args) {
      HashSet<Integer> hm = new HashSet<>();
      hm.add(12);
      hm.add(20);
      hm.add(35);
      Iterator<Integer> iterator = hm.iterator();
      int first= iterator.next();
      int last = 0;
      for (int x : hm) {
         last = x;
      }
      System.out.println("First element of HashSet: " + first);
      System.out.println("Last element of HashSet: " + last);
   }
}

Output

First element of HashSet: 35
Last element of HashSet: 12

Approach 2: Using toArray() method

In this example, we create a HashSet object and add a few elements to the hasSet using add() method and then we convert the HashSet to array using toArray() method. Then access the first and last elements of the array and then print them.

Algorithm

  • Create a HashSet instance and add elements to the set using the add() method.

  • Convert the set into an array object using the toArray() method.

  • Retrieve the first element and last element of the array using indexes and print it.

Example

In this example, we will convert a set to an array using ‘toArray()’ method and then we will find the first and last element of HashSet.

import java.util.HashSet;

public class Main {
   public static void main(String[] args) {
      HashSet<String> hm = new HashSet<>();
      hm.add("apple");
      hm.add("banana");
      hm.add("cherry");   
      // Convert the set to an array
      String[] arr = new String[hm.size()];
      hm.toArray(arr); 
      // Find the first and last elements of the array
      String first = arr[0];
      String last = arr[arr.length - 1];
      System.out.println("First element: " + first);
      System.out.println("Last element: " + last);
   }
}

Output

First element: banana
Last element: cherry

Thus, in this article we have learnt how to get the first and last element of a HashSet using different approaches in Java.

Updated on: 16-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements