![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
How to save the elements of a TreeSet to a file in Java?
A TreeSet is a subclass of AbstractSet class and it does not allow duplicate elements. By default, TreeSet stores the elements in an ascending order and retrieval speed of an element out of a TreeSet is faster. The TreeSet class internally uses a TreeMap to store elements. The elements in a TreeSet are sorted according to their natural ordering.
We can also save the elements stored in a TreeSet to a file by using the Arrays.asList() method and pass this set as an argument to the writeObject() method of ObjectOutputStream class.
Syntax
public class TreeSet extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
Example
import java.util.*; import java.io.*; public class TreeSetTest { public static void main(String args[]) { try { String elements[] = {"Raja", "Jai", "Adithya", "Chaitanya"}; Set<String> set = new TreeSet<String>(Arrays.asList(elements)); FileOutputStream fos = new FileOutputStream("set.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(set); oos.close(); System.out.println("The elements of a Set saved to a File Sucessfully"); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); } } }
Output
The elements of a Set saved to a File Sucessfully
Advertisements