How to Delete User Defined Objects from LinkedHashSet?
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.
Example:
Input: ["Geeks", "for", "geeks"]
DELETE = "geeks"
Output: "Geeks"
"for"
Input: [1, 2, 3, 4, 5]
DELETE = 2
Output: [1, 3, 4, 5]
There are two ways by which we can delete elements from LinkedHashSet:
- Using remove() Method
- Using clear() Method
Method 1: remove() methods are used to delete a specific element from a LinkedHashSet object.
Syntax:
LinkedHashSet.remove(Object O)
Parameters: The parameter O is of the type of LinkedHashSet and specifies the element to be removed from the LinkedHashSet.
Return Value: This method returns True if the specified element is present in the LinkedHashSet otherwise it returns False.
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
LinkedHashSet<String> lset
= new LinkedHashSet<String>();
lset.add( "GEEKS" );
lset.add( "FOR" );
lset.add( "GEEKS" );
System.out.println( "Before deleting an element :" );
System.out.println(lset);
lset.remove( "FOR" );
System.out.println( "After deleting an element:" );
System.out.println(lset);
}
}
|
Output
Before deleting an element :
[GEEKS, FOR]
After deleting an element:
[GEEKS]
Method 2: clear() method is used to delete all element from LinkedHashSet. The set will be empty after this call returns.
Syntax:
public void clear()
Return Value: This method does not return anything.
Below are the examples to illustrate the clear() method.
Java
import java.util.*;
import java.util.LinkedHashSet;
public class GFG {
public static void main(String[] args)
{
LinkedHashSet<String> l_set
= new LinkedHashSet<String>();
l_set.add( "GEEKS" );
l_set.add( "FOR" );
l_set.add( "GEEKS" );
System.out.println( "Before deleting an element :" );
System.out.println(l_set);
l_set.clear();
System.out.println( "After deleting all element:" );
System.out.println(l_set);
}
}
|
Output
Before deleting an element :
[GEEKS, FOR]
After deleting all element:
[]
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...