Open In App

How to Delete User Defined Objects from LinkedHashSet?

Last Updated : 28 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Using remove() Method
  2. 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.


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.


Output
Before deleting an element :
[GEEKS, FOR]
After deleting all element:
[]

Next Article
Practice Tags :

Similar Reads