How to Get the Last Element from LinkedHashSet in Java?
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 in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.
There are two ways by which we can get the last element from LinkedHashSet:
- By iterating the Set.
- By converting the LinkedHashSet to array or list.
Method 1: By iterating the Set
By iterate LinkedHashSet: To get the last element from LinkedHashSet by iterate LinkedHashSet, the process divided into two parts:
- First, make a variable lastEle
- Iterate LinkedHashSet and get the last element
Example:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add( 10 );
set.add( 20 );
set.add( 30 );
set.add( 10 );
set.add( 50 );
set.add( 20 );
int lastEle = 0 ;
for ( int x : set)
{
lastEle = x;
}
System.out.println( "LinkedHashSet: " + set);
System.out.println( "Last element of LinkedHashSet: "
+ lastEle);
}
}
|
Output
LinkedHashSet: [10, 20, 30, 50]
Last element of LinkedHashSet: 50
Method 2: By converting the LinkedHashSet to Array
To get the last element from LinkedHashSet using Array, the process divided into three parts:
- First, make an Array.
- Convert LinkedHashSet to Array with the help of toArray() method.
- Get the last element using the last index.
Example:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add( 10 );
set.add( 20 );
set.add( 30 );
set.add( 10 );
set.add( 50 );
set.add( 20 );
Integer[] elements = new Integer[set.size()];
elements = set.toArray(elements);
int lastEle = elements[elements.length - 1 ];
System.out.println( "LinkedHashSet: " + set);
System.out.println( "Last element of LinkedHashSet: "
+ lastEle);
}
}
|
Output
LinkedHashSet: [10, 20, 30, 50]
Last element of LinkedHashSet: 50
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...