HashSet remove() Method in Java

Published by user on

The remove(Element e) method of HashSet removes the specified element from the set.

Syntax

boolean remove(Element e)

Parameters

e is the element to be removed

Return Value

It returns true on successful removal of the element otherwise false if the element is not found in the HashSet.

Program

import java.util.HashSet;

public class HashSetRemoveExample {

	public static void main(String[] args) {

		HashSet<Integer> set = new HashSet<>();
		set.add(10);
		set.add(20);
		set.add(30);
		set.add(40);
		set.add(50);

		System.out.println("Set elements : " + set);

		set.remove(20);
		System.out.println("Set elements after removing 20: " + set);
		set.remove(00);// returns false if element not found in set
	}
}

Output

Set elements : [50, 20, 40, 10, 30]
Set elements after removing 20: [50, 40, 10, 30]
Categories: Java

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *