Back to articles
TreeSet in Java

TreeSet in Java

via Dev.to TutorialNanthini Ammu

What is TreeSet? Stores unique elements. Maintains elements in sorted order (ascending by default). Does not allow duplicates. It is part of the Java Collections Framework in Java and implements the Set interface. Example : import java.util.TreeSet; public class Learn { public static void main(String[] args) { TreeSet tr = new TreeSet(); tr.add(1000); tr.add(300); tr.add(500); tr.add(10); System.out.println(tr); } } //Even though we inserted 1000 first, TreeSet keeps them sorted. Output: [10, 300, 500, 1000] Duplicate Example : import java.util.TreeSet; public class Learn { public static void main(String[] args) { TreeSet tr = new TreeSet(); tr.add(1000); tr.add(1000); tr.add(500); tr.add(500); System.out.println(tr); } } //Duplicate values are ignored. Output : [500, 1000] Null Example : import java.util.TreeSet; public class Learn { public static void main(String[] args) { TreeSet tr = new TreeSet(); tr.add(null); System.out.println(tr); } } //TreeSet does not allow null. Output : Nu

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles