Skip to content
Related Articles

Related Articles

Java Program to Get First or Last Elements from HashSet
  • Last Updated : 11 Dec, 2020

The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. There is no guarantee made for the iteration order of the set which means that the class does not guarantee the constant order of elements over time. This class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets, which we shall see further in the article. 

The HashSet does not guarantee the constant order of elements over time, which means when we iterate a HashSet, there is no guarantee that we get the same order of elements as we added in order. So there is no first or last element in HashSet. But, we can find the first or last element in the HashSet according to how it stores the elements. Through simple iterate over the HashSet.

Approaches:

  1. The naive approach to insert, add then display desired elements.
  2. Using the stream, with the help of the findFirst() and get() inbuilt methods.

Example 1: Printing the first element and last element of HashMap. 

Java




// Java Program to Get First or
// Last Elements from Java HashSet
  
// Importing java generic libraries
import java.util.*;
  
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating a HashSet
        HashSet<Integer> set = new HashSet<>();
  
        // Add data to Hashset
        set.add(10);
        set.add(20);
        set.add(20);
        set.add(10);
        set.add(50);
        set.add(40);
  
        // Initializing first elemnt as 0 from ourside
        // instead of garbage valu involvement
        int firstEle = 0;
  
        // Iterate HashSet using for rach loop
        for (int val : set) {
            firstEle = val;
            break;
        }
  
        // int lastEle = 0;
  
        // Print HashSet
        System.out.println("HashSet : " + set);
  
        // Print First element
        System.out.println("First element of HashSet : "
                           + firstEle);
    }
}
Output



HashSet : [50, 20, 40, 10]
First element of HashSet : 50

Method 2: Using streams to find the first element in HashSet, with the help of the findFirst() and get() methods in Java. 

Syntax:

set.stream().findFirst().get()

Return Type: Returning the first element of the HashMap

Exceptions: If HashSet is empty get() throws an error(java.util.NoSuchElementException).

 Example:

Java




// Java code to find the first element
// in HashSet with the help of stream
  
// Importing generic java libraries
import java.util.*;
  
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating a new HashSet
        HashSet<Integer> set = new HashSet<>();
  
        // Add data to Hashset
        set.add(10);
        set.add(20);
        set.add(20);
        set.add(10);
        set.add(50);
        set.add(40);
  
        // Find the first element in HashSet
        // using stream and findFirst method
        int firstEle = set.stream().findFirst().get();
  
        // Print HashSet
        System.out.println("HashSet : " + set);
  
        // Print First element of HasSet
        System.out.println("First element of HashSet : "
                           + firstEle);
    }
}
Output
HashSet : [50, 20, 40, 10]
First element of HashSet : 50

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :