Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the LinkedHashSet.remove method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The LinkedHashSet is similar to the HashSet, except that LinkedHashSet maintains the insertion order of elements, whereas HashSet does not. Read more about LinkedHashSet here.

The remove() method removes an element from the LinkedHashSet object.

Syntax

public boolean remove(Object o)

Parameters

This method takes the element to be removed from the set as an argument.

Return value

The remove() method returns true if the passed element is present and removed from the set. Otherwise, it returns false.

Code

import java.util.LinkedHashSet;
class Remove {
public static void main( String args[] ) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(1);
set.add(2);
set.add(3);
System.out.println("The set is " + set);
System.out.println("Calling set.remove(3). Is removed - " + set.remove(3));
System.out.println("Calling set.remove(4). Is removed - " + set.remove(4));
System.out.println("The set is " + set);
}
}
Using LinkedHashSet

Explanation

In the code above, we take the following steps:

  • In line number 1, we import the LinkedHashSet class.

  • In line number 4, we create a new LinkedHashSet object with the name set.

  • From line numbers 5 to 7, we use the add method to add three elements (1,2,3) to the set object.

  • In line number 10, we use the remove() method to remove the element 3 from the set. The element 3 is present in the set, so the element is removed from the set and true is returned.

  • In line number 11, we use the remove() method to remove the element 4 from the set. The element 4 is not present in the set, so false is returned.

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring