Java Set remove() method with Examples

In this tutorial we will see how to remove element from Set . We will see how to remove given element with comparator, remove first element and  remove last element from Set in java.

Java Set remove() method Examples

Now we will see different approaches of remove element from Set in Java . We will discus each approaches with examples as following .

1. Remove Element From Set – Remove() Method Example

We can remove given element from Set Using remove() method. Set remove() method removes the specified element from this set if it is present.

Syntax :

public boolean remove(Object o) {

   }

Parameters – It’s take o object to be removed from this set, if present
Returns Value – It’s return true if this set contained the specified element
Exception – It’s throws following exceptions
ClassCastException : throws if the type of the given element is incompatible with this set (optional)
NullPointerException : throws if the given element is null and this set does not permit null elements (optional)
UnsupportedOperationException – throws if the remove operation is not supported by this set

import java.util.Set;
import java.util.TreeSet;

public class RemoveElement {

public static void main(String[] args) {

Set<String> ts = new TreeSet<String>();
ts.add("mumbai");
ts.add("delhi");
ts.add("kolkata");
ts.add("chandigarh");
ts.add("dehradun");

// print treeset
System.out.println(" Before Remove Tree Set is = ="+ts);

/*
* Removes the specified element from this
*  set if it is present
*/

ts.remove("delhi");

System.out.println(" After Remove Tree Set is = "+ts);

}

}

Output:

Before Remove Tree Set is = =[chandigarh, dehradun, delhi, kolkata, mumbai]

After Remove Tree Set is = [chandigarh, dehradun, kolkata, mumbai]

We can remove custom object from TreeSet

import java.util.Set;
import java.util.TreeSet;

public class TreeSetRemove {
	
	public static void main(String[] args) {

		Set<User> treeSet = new TreeSet<User>();
		treeSet.add( new User(1,"amit"));
		treeSet.add( new User(2,"ankit"));
		treeSet.add( new User(3,"anup"));

		// print treeset
		System.out.println("Before Remove Tree Set is = ="+treeSet);

		/*
		* Removes the specified element from this
		*  set if it is present
		*/
		treeSet.remove(new User(2,"ankit"));
		System.out.println("After Remove Tree Set is = "+treeSet);
	}

}


class User implements Comparable<User>{
	private int id;
	private String name;
	

	public User(int id ,String name) {
		super();
		this.name = name;
		this.id = id;
	}

	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "User [name=" + name + ", id=" + id + "]";
	}

	@Override
	public int compareTo(User o) {
		 if (id > o.id) { 
	            return 1; 
	        } 
	        else if (id < o.id) { 
	            return -1; 
	        } 
	        else { 
	            return 0; 
	        } 
	}
	
	
}

Output :

Before Remove Tree Set is = 
[User [name=amit, id=1], User [name=ankit, id=2], User [name=anup, id=3]]
After Remove Tree Set is = 
[User [name=amit, id=1], User [name=anup, id=3]]

A custom object must implement Comparable interface or custom comparator when It’s add to TreeSet object.

2. Remove first element From Set

We can remove first element from Set with the help of pollFirst() method. pollFirst() method  retrieves and removes the first (lowest) element, or returns null if this Set is empty.

Syntax :

public E pollFirst() {

}

Returns Value –  It’s the first element, or null if this set is empty .

Let’s see how treeset remove first item in java.

import java.util.TreeSet;

public class TreeSetRemoveExample {

	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("mumbai");
		treeSet.add("delhi");
		treeSet.add("kolkata");
		treeSet.add("chandigarh");
		treeSet.add("dehradun");

		// print treeset
		System.out.println(" Before Remove Tree Set is = ="+treeSet);

		 String firstElement = treeSet.pollFirst();
		 System.out.println("first element is ="+ firstElement);
		System.out.println(" After Remove Tree Set is = "+treeSet);

		
	}
}

Output :

Before Remove Tree Set is = =[chandigarh, dehradun, delhi, kolkata, mumbai]
 first element is =chandigarh
 After Remove Tree Set is = [dehradun, delhi, kolkata, mumbai]

3. Remove Last Element From Set

Set pollLast() method can remove last element from Set.pollLast() Method retrieves and removes the last (highest) element, or returns null if this set is empty.

Syntax :

public E pollLast() {

  }

Returns Value – It’s the last element, or null if this set is empty

public class TreeSetRemoveExample {

	public static void main(String[] args) {
		TreeSet<String> treeSet = new TreeSet<String>();
		treeSet.add("mumbai");
		treeSet.add("delhi");
		treeSet.add("kolkata");
		treeSet.add("chandigarh");
		treeSet.add("dehradun");

		// print treeset
		System.out.println(" Before Remove Tree Set is = ="+treeSet);

		//Retrieves and removes the last element
		String lastElement = treeSet.pollLast();
		
		System.out.println("last element is ="+ lastElement);
		System.out.println(" After Remove Tree Set is = "+treeSet);

		
	}
}

Output :

Before Remove Tree Set is = =[chandigarh, dehradun, delhi, kolkata, mumbai]
last element is =mumbai
 After Remove Tree Set is = [chandigarh, dehradun, delhi, kolkata]

In this tutorial we have learn about java remove() method . You can see How to remove All element from TreeSet . I can see more TreeSet Example In Java , and learn different type things with TreeSet.

Reference :

A Guide To Java Collection                                                                                                    Java Doc – TreeSet

Leave a Reply

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

1 + 5 =