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
raja
Published on 11-Sep-2019 16:26:42
Advertisements