How To Remove Element From TreeSet

Assuming you have gone through TreeSet in Java , In this post we will see how to remove element from TreeSet. In this post we will see how to remove given element , remove element with comparator , remove first element and  remove last element from TreeSet in java.

How to remove an element from TreeSet in java ?

Now we will see couple of ways for remove element from TreeSet in Java

1. Remove Given Element From TreeSet – Remove() Method Example

We can remove given element from TreeSet 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 custome object must implement Comparable interface or custom comparator when It’s add to TreeSet object.

2. Remove first element From TreeSet

We can remove first element from treeset 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 TreeSet

TreeSet pollLast() method can remove last element from TreeSet.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 post we have learn how to remove items from TreeSet . 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 *

5 + = 7