Java Program to Get the First Element from LinkedHashSet
Last Updated :
24 Dec, 2021
LinkedHashSet is an implementation of Set Abstract Data Type (ADT). It extends from the HashSet class which in-turn implements Set Interface. The difference between the LinkedHashSet and HashSet is the property of maintaining the element ordering. LinkedList is just a container holding sequence of elements. By definition, Set should not contain duplicate elements. This property need not hold good for the LinkedList ADT. When elements should be duplicated and the order has to be maintained, one should use LinkedHashSet.
Methods:
There are basically three standard ways to get an element from LinkedHashSet without changing it to a different data structure.
- Converting it to an array or List
- Using Iterators
- Using Streams
Implementation: Getting the First Element from LinkedHashSet
Method 1: By converting it to an array or List
Example
Java
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws java.lang.Exception
{
LinkedHashSet<Integer> hashSet
= new LinkedHashSet<Integer>();
hashSet.add( 2 );
hashSet.add( 1 );
hashSet.add( 4 );
hashSet.add( 6 );
hashSet.add( 8 );
if (!hashSet.isEmpty()) {
Integer arr[] = new Integer[hashSet.size()];
arr = hashSet.toArray(arr);
System.out.println( "First element: " + arr[ 0 ]);
}
}
}
|
Method 2: Using Iterators
Example
Java
import java.util.*;
import java.lang.*;
import java.io.*;
public class GFG {
public static void main(String[] args)
throws java.lang.Exception
{
LinkedHashSet<Integer> hashSet
= new LinkedHashSet<Integer>();
hashSet.add( 1 );
hashSet.add( 2 );
hashSet.add( 3 );
hashSet.add( 4 );
hashSet.add( 5 );
Iterator<Integer> iter = hashSet.iterator();
if (iter != null && iter.hasNext()) {
System.out.println(
"First element in LinkedHashSet: "
+ iter.next());
}
}
}
|
Output
First element in LinkedHashSet: 1
Method 3: Using Streams
Example:
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args) throws java.lang.Exception
{
LinkedHashSet<Integer> hashSet
= new LinkedHashSet<Integer>();
hashSet.add( 1 );
hashSet.add( 2 );
hashSet.add( 3 );
hashSet.add( 4 );
hashSet.add( 5 );
if (hashSet.size() == 0 )
System.out.println( "The Set is Empty!" );
else {
int first = hashSet.stream().findFirst().get();
System.out.println(
"First element in LinkedHashSet: " + first);
}
}
}
|
Output
First element in LinkedHashSet: 1
Share your thoughts in the comments
Please Login to comment...