I have a Set that contains different random lines from a text file, now I'm new to Java so I don't know much about the methods available but I have tried using the java.util.Set.toArray() method but it returns an Object[] than can not be sorted.

Is there anyway to do this? any help would be appreciated.

Thank you.

If you are developing in Java 1.5 consider using generics in which you can make toArray() of Set return an array of T[] where T is the type of element you have stored in your Set.

Set<String> s = obj.someMethod();
String[] sArr = s.toArray(new String[s.size()]);

Alternatively, you can create a TreeSet out of your given Set which guarantees that its elements are always ordered.

Set s = obj.someMethod();
s = new TreeSet(s);
// s now contains elements sorted according to their
// natural ordering

Also, if you are in control of the method which returns a Set , you can modify the logic to store the elements in a TreeSet from the start which will do away with the need of performing a sort later on i.e. sort as you add.


import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class BlackRobe {

    public static void main(String args[]) {
        SortedSet<String> set = new TreeSet<String>();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String s = it.next();
This article has been dead for over six months. Start a new discussion instead.