Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How To Implement Treeset In Java?

Published on Aug 07,2019 2.2K Views

18 / 22 Blog from Java Collections

We all know that Collections play a major role in any java application. It provides various classes and interfaces which further provides their own sub classes and implementations. Treeset in Java is one such part of collections which naturally stores the data in ascending order without allowing any duplications. Let us understand what treeset is, in detail,

Following pointers will be covered in this article,

Moving on with this article on Treeset

Treeset In Java

Set<String> syncTreeSet = Collections.synchronizedSet(syncTreeSet);

Also treeset class doesn’t allow any null values.  Now lets see an example/

import java.util.*;  
class TreeSet1{  
public static void main(String args[]){  
TreeSet<String> treeSet=new TreeSet<String>();  
treeSet.add("Java");  
treeSet.add("Python");  
treeSet.add("Cobol");  
Iterator<String> itr=treeSet.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
} 
}  
}  

Output:
Cobol

Java

Python 

Since its an ordered class the output is as shown above.

Moving on with this article on Treeset

Treeset Function

Now lets see the constructors provided by the treeset class. It provides four constructors.

ConstructorDescription
TreeSet( )                                                Creates an empty treeset with default sorted order.
TreeSet(Collection c)Creates a treeset with the elements of the collection c.
TreeSet(Comparator comp)Creates an empty treeset with the given comparator order for sorting the elements ewhilestoring it.
TreeSet(SortedSet s)Creates a treeset with the elements of the sortedset s.

Moving on with this article on Treeset

Treeset Methods

Additional to these constructors, treeset provides many methods as given below.

MethodDescription
void add(Object o)Adds an element to treeset if it is not already present
boolean AddAll(Collection c)Adds all the elements of the given collection to treeset
Object clone()Returns a shallow copy of that treeset instance i.e a copied set
Object first()Returns first(lowest) element stored in the treeset
Object last()Returns last(highest) element stored in the treeset
boolean isEmpty()Returns true if the treeset is empty(no elements present in it)
boolean contains(Object o)Returns true if treeset contains given element
void clear()This will remove all the elements
SortedSet headset(Object toElement)Returns all the elements of treeset which are less than the given element
SortedSettailSet(Object fromElement)Returns all the elements of treeset which are greater than or equal to the given element
SortedSet subset(Object fromElement,ObjecttoElement)Returns all elements in between the given range (including fromElement and excluding toElement)
int size() Returns the size of treeset( number of elements present)
Iterator iterator()Returns an iterator to iterate over the elements of the set
boolean remove(Object o)Removes the specified element if present
SortedSet descendingSet()Returns reverse order of the given set
pollFirst()Removes first(lowest) element from the set
pollLast()Removes last(greatest) element from the set
lower(E e)Returns greatest element in the set which is strictly less than the given element or null if such element is not present
higher(E e)Returns least element in the set which is strictly greater than the given element or null if such element is not present
Comparator comparator()Returns the comparator used to order the elements of the set or null if no such comparator is used and natural ordering is used to sort
Spliterator spliterator()Creates a late-binding and fail-fast spliterator over the elements
floor(E e)Returns the equal or closest least element of the specified element from the set, or null there is no such element
ceiling(E e)Returns the equal or greatest least element of the specified element from the set, or null there is no such element
Iterator descendingIterartor()Used to iterate elements in descending order.

 

Moving on with this article on Treeset

Program For Treeset In Java

Now lets  see an example program with some of these functions. 

importjava.util.Iterator;
importjava.util.TreeSet;
public class Sample {
publicstaticvoid main(String args[]){  
TreeSet<String>ol=newTreeSet<String>();  
ol.add("India");  
ol.add("Australia");  
ol.add("India");  
ol.add("Canada"); 
ol.add("Nepal");
ol.add("China");	
Iterator itr=ol.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  	
System.out.println("Size:"+ol.size());	
itr=ol.descendingIterator();
System.out.println("Elements in reverse order");
while(itr.hasNext()){  
System.out.println(itr.next());  
}	
System.out.println("Initial Set:"+ol);  
System.out.println("Reverse Set:"+ol.descendingSet());  
System.out.println("Head Set:"+ol.headSet("India"));  
System.out.println("SubSet:"+ol.subSet("China", "Nepal"));  
System.out.println("TailSet:"+ol.tailSet("Canada"));	
System.out.println("Highest Value:"+ol.pollFirst()); 
System.out.println("Lowest Value:"+ol.pollLast());
System.out.println("After poll operations:"+ol);
ol.remove("China");
System.out.println("After a removal:"+ol);
ol.add("Australia"); 
ol.add("Netherlands"); 
if(ol.contains("India")){
System.out.println("the given set contains India");
}	
ol.clear();
System.out.println("set after clear operation:"+ol);	
}
}

Output:

Australia

Canada

China

India

Nepal

Size:5

Elements in reverse order

Nepal

India

China

Canada

Australia

Initial Set:[Australia, Canada, China, India, Nepal]

Reverse Set:[Nepal, India, China, Canada, Australia]

Head Set:[Australia, Canada, China]

SubSet:[China, India]

TailSet:[Canada, China, India, Nepal]

Highest Value:Australia

Lowest Value:Nepal

After poll operations:[Canada, China, India]

After a removal:[Canada, India]

the given set contains India

set after clear operation:[]

Thus we have come to an end of this article on ‘Treeset In Java’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Implement Treeset In Java?

edureka.co