Java Program to Get First or Last Elements from HashSet
Last Updated :
05 Sep, 2023
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:
- The naive approach to insert, add then display desired elements.
- 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 element as 0 from outside
// instead of garbage value involvement
int firstEle = 0;
// Iterate HashSet using for each 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);
}
}
OutputHashSet : [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();
// Find the first element in HashSet
int lastEle = set.stream().reduce((a,b)->b).get();
// Print HashSet
System.out.println("HashSet : " + set);
// Print First element of HashSet
System.out.println("First element of HashSet : "
+ firstEle);
// Print Last element of HashSet
System.out.println("Last element of HashSet : "
+ lastEle);
}
}
OutputHashSet : [50, 20, 40, 10]
First element of HashSet : 50
Similar Reads
Java Program to Get Elements By Index from LinkedHashSet LinkedHashSet is a pre-defined class in Java that is similar to HashSet. Unlike HashSet In LinkedHashSet insertion order is preserved. In order to get element by Index from LinkedHashSet in Java, we have multiple ways.Illustration:Input : 2, 3, 4, 2, 7;Processing : index = 4;Output : Element at inde
4 min read
How to Get First and Last Element From the Vector in Java? The first element in the Vector can be obtained using the firstElement() method of vector class that is represent util package. The last element in the Vector can be obtained using the lastElement() method of vector class that is also represent util package. Neither of these methods requires any par
2 min read
Java Program to Iterate LinkedHashSet Elements The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
3 min read
How to Get First or Last Entry from Java LinkedHashMap? LinkedHashMap is a predefined class in Java which is similar to HashMap, containing key and its respective value unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to get the first and last entry present in LinkedHashMap. Iteration to get last and first value. The first and t
5 min read
Java Program to Get the First and the Last Element of a Linked List A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The given task is to retrieve the first and the last element of a given linked list. Properties of a Linked ListElements are stored in a non-contiguous manner.Every element is an object whi
4 min read
Java Program to Convert List to HashSet The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. The HashSet class permits the null element. The class al
4 min read