top of page

Java Collections : Stack , Tree Map and Tree Set Part 4

In this blog we will be learning all the operations we can do in Stack , Tree Map and Tree Set ,this blog will be very useful for those want to learn Java Collections


Stack in Java usually means the class from Collection Framework that implements the List interface. It works on the principle of the Stack data structure, which is used to organize one of the types of memory.

* Stack -> child class of Vector * Follows LIFO (Last In First Out) //stack and vector are legacy classes as it is there from the frist version of java //child class of vector //Follows LIFO(Last In First Out)

package collections;

import java.util.Stack;

public class StackExample {

	public void stackExample() {

		//create Object
		Stack<String> stack= new Stack<String>();
		// to insert  an element --> push()
		//To print and see the satck
		System.out.println(" stack element : "+ stack);
		//delete an element --> pop()
		stack.pop();  //LIFO , so the last inserted element will be deleted
		System.out.println(" after popping an element : "+ stack);
		// to get the top element--> peek()
		System.out.println(" Top element : "+ stack.peek());
		// search returns the offset value. Offset is the position counted from top
		System.out.println(" saerching the element A : "+"A"));
		// If the element is not present then the value =-1
		System.out.println(" searching an element which is not present :" +"x"));
	public static void main(String[] args) {
		StackExample example= new StackExample();


Tree Map

The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in an ascending key order.

package collections;

import java.util.TreeMap;

public class TreeMapExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeMap<String,String> placesInPondy=new TreeMap<String,String>();
		placesInPondy.put("beach", "Pondy");		
		placesInPondy.put("park", "Pondy");
		placesInPondy.put("auroville", "Pondy");
		placesInPondy.put("temple", "Pondy");
		placesInPondy.put("marina", "Pondy");
		// duplicate key not allowed
		placesInPondy.put("pondy", "chennai");
		placesInPondy.put("pondy", "puthur");   // overwrites value ,18 line for same key 
		// if key is null , null point inserrtion, no null insertion in tree map , tree means sorting order 
		placesInPondy.put(null, "Pondy");
		placesInPondy.put(null, "chennai");
		// java.lang.NullPointerException		



TreeSet is a sorted collection that extends the AbstractSet class and implements the NavigableSet interface. Here's a quick summary of the most important aspects of this implementation: It stores unique elements. It doesn't preserve the insertion order of the elements.

	 * TreeSet is the implementation class of SortedSet Interface.
	 * Does not allow duplicates.
	 * Sorts the elements
	 * It has 6 methods like first,last,headSet,tailSet,subSet and comparator.
	 * Difference between Hashset and Treeset, hash doesnt maintain order
	 * but Treeset maintains ascending or alphabetical order.
	 * DS-> Balanced Tree
	 * Heterogeneous data not allowed. If added Exception, ClassCast will occur
	 * For default natural sorting order,the objects should be homogeneous and comparable else class cast exception
	 * To say any class is comporable or not, the class should implement comparable interface.

	 Number of Constructors 
	 * 1. TreeSet ts= new TreeSet();// default sort order
	 * 2. TreeSet ts= new TreeSet(Comparator c);// customized sorting order defined by comparator object
	 * 3. TreeSet ts= new TreeSet(Collection c);// equivalent tree set of any collection will be created
	 * 4. TreeSet ts= new TreeSet(SortedSet s);// creates tree set for given sorted set
package collections;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

	public void treeSetExample() {
		//creating object
		TreeSet<Integer> treeSet=new TreeSet<Integer>();
		//treeSet.add(null); //Exception in thread "main" java.lang.NullPointerException:
		//Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null
		//treeSet.add(null); //Exception in thread "main" java.lang.NullPointerException
		System.out.println(" elements are soreted in ascending order in treeset : " + treeSet);
		System.out.println(" first element :"+ treeSet.first());
		System.out.println(" last element : "+ treeSet.last());
		System.out.println(" values lesser than given value :"+ treeSet.headSet(3));
		System.out.println(" values equal to and higher than given value :"+treeSet.tailSet(3));
		System.out.println(" subset values :"+ treeSet.subSet(2,9));
		System.out.println("comparator returns null if the sorting is default natural order: "+treeSet.comparator());
		TreeSet<StringBuffer> set = new TreeSet<StringBuffer>();
		set .add(new StringBuffer("B"));
		set .add(new StringBuffer("A"));
		System.out.println(" string buffer compartaor  : "+ set);
		//  returns null if we did not explicitly sepcify to arrange in the order
	//Adding null to a non empty tree set causes null pointer excpetion
			/*null can be easily added if the tree set is empty(until 1.6 version). If there are any elements present, the
			 * comparator will check for the sorting order between the previosly added element and 
			 * the null. Since it compares null with the objects exisiting we are getting NPE.
			 * Same is the case, if we add null first and add other elements, NPE will happen.
		System.out.println(" immediate higher value : " + treeSet.higher(5));
		System.out.println("immediate lower value : " + treeSet.lower(2));
		System.out.println(" contains element :"+treeSet.contains(5));
		System.out.println(" size of tree set :"+ treeSet.size());
		//pollFirst  [ retrieve and delete ]
		System.out.println(" poll first :"+treeSet.pollFirst());
		//pollLast [ retrieve and delete]
		System.out.println(" poll last :"+treeSet.pollLast());
		System.out.println(" after polling : "+ treeSet);
		System.out.println(" descending order set  : "+ treeSet.descendingSet());
	    System.out.println("after removing an element :"+treeSet);
	// normal iteration
	    Iterator<Integer> iterator= treeSet.iterator();
	    	System.out.println(" printing in order :"+;
	     Iterator<Integer>  descIterator= treeSet.descendingIterator();
	     while(descIterator.hasNext()) {
	    	 System.out.println(" printing in descending order :";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSetExample example= new TreeSetExample();



I hope, This article will help you to understand Stack , Tree Set and Tree Map on how to add , remove , insert , update , delete, iterate ....

Please Refer Part 1 for Array List and Linked List

Please Refer Part 2 for Map and Set.

Please Refer Part 3 for Linked Hash Map , Linked Hash Set and Vector

You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.

Happy Learning

397 views0 comments
bottom of page