TreeMap and TreeSet in Java
0 246
๐ณ TreeMap and TreeSet in Java
In the world of Java collections, TreeMap and TreeSet in Java are powerful tools when you need data to be stored in a naturally sorted order. Both are part of the Java Collections Framework and are implemented using Red-Black Trees, ensuring log(n) time complexity for basic operations like insertion, removal, and lookup.
๐ What is TreeMap?
A TreeMap
is a map that stores key-value pairs in sorted order according to the keys. It does not allow null keys and uses natural ordering or a specified comparator.
This makes it perfect when you need ordered maps with efficient access.
import java.util.TreeMap;
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "C++");
map.put(1, "Java");
map.put(2, "Python");
System.out.println(map); // Outputs: {1=Java, 2=Python, 3=C++}
๐ Features of TreeMap
- Stores key-value pairs in ascending key order
- Does not allow null keys
- Implements
NavigableMap
andSortedMap
- Supports custom ordering using
Comparator
๐ฟ What is TreeSet?
A TreeSet
is a collection that stores unique elements in sorted order. It is ideal when you want to maintain a set of non-duplicate elements in a naturally ordered fashion.
Like TreeMap, TreeSet is based on the Red-Black tree algorithm.
import java.util.TreeSet;
TreeSet<String> set = new TreeSet<>();
set.add("Banana");
set.add("Apple");
set.add("Mango");
System.out.println(set); // Outputs: [Apple, Banana, Mango]
๐ Features of TreeSet
- Stores unique elements in sorted order
- Does not allow null elements (throws exception)
- Implements
NavigableSet
andSortedSet
- Supports custom comparators for sorting logic
โ๏ธ Common Methods
- TreeMap:
put()
,get()
,remove()
,firstKey()
,lastKey()
- TreeSet:
add()
,remove()
,contains()
,first()
,last()
๐ When to Use TreeMap or TreeSet?
- Use
TreeMap
when you need a sorted dictionary-like structure with key-value pairs. - Use
TreeSet
when you want to store unique elements in a specific order. - Both are perfect for range-based operations and ordered traversals.
โ Conclusion
Understanding how to use TreeMap and TreeSet in Java
gives you control over sorted data in your applications.
Whether you're building search indexes, leaderboards, or auto-suggestion features, these sorted structures make your work easier and more efficient.
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments