- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Sub Set from TreeSet in Java
To get the sub set from TreeSet, use the subSet() method. Let us first create a TreeSet and add elements to it −
TreeSet<String> set = new TreeSet<String>(); set.add("78"); set.add("56"); set.add("88"); set.add("54"); set.add("76"); set.add("34");
Let us get the subset now from a range of elements −
SortedSet sorted = set.subSet("54", "76");
The following is an example to get sub set from Java TreeSet −
Example
import java.util.*; public class Demo { public static void main(String args[]){ TreeSet<String> set = new TreeSet<String>(); set.add("78"); set.add("56"); set.add("88"); set.add("54"); set.add("76"); set.add("34"); System.out.println("TreeSet elements..."); Iterator<String> i = set.iterator(); while(i.hasNext()){ System.out.println(i.next()); } SortedSet sorted = set.subSet("54", "76"); System.out.println("SubSet = " + sorted); } }
Output
TreeSet elements... 34 54 56 76 78 88 SubSet = [54, 56]
Advertisements