TreeSet For Sorting Order

Posted: 21st November 2012 by Peter in Java
Tags: , , ,

We’re covering ‘Collections’, ‘Collection’ and erm…’collection’ in Java Programmer 6 at the moment. I’m familiarizing myself with the various Sets, Lists and Maps.

A TreeSet orders its elements using ‘natural ordering’, i.e. alphabetical order for Strings, numerical order for ints. This is a very useful feature of the TreeSet that I wanted to experiment with. I wrote the following program that uses an overloaded method ‘getSortedTreeSet’ that will take a String array, or an int array, and return them as an ordered String for output.

/*
* Take in a String array, sort the contents into alphabetical order
* and return the ordered contents as a String. Then do the same for an
* int array, overloading the method.
*/

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class SetsListsMaps {

public static void main(String[] args) {

//String array and related String method output
String[] strAr = {"b","c","f","a","d","e","i","h","j","g"};
System.out.println(getSortedTreeSet(strAr));

//int array and related String method output
int[] intAr = {9, 5, 1, 8, 4, 6, 2, 3, 7, 0};
System.out.println(getSortedTreeSet(intAr));
}
//method

public static String getSortedTreeSet(String[] ar) {
String str = "";
String[] myStrAr = ar;

//create TreeSet...
Set set = new TreeSet();
for (String strTemp : myStrAr) {
set.add(strTemp);
}

//TreeSet to String
//Iterator hasNext() and next()
Iterator iter = set.iterator();
while (iter.hasNext()) {
str += (String) iter.next() + " ";
}
return str;
}

//The following is the same as above, but with Integers
public static String getSortedTreeSet(int[] ar) {
String result = "";
int[] myInt = ar;

//create TreeSet...
Set set = new TreeSet();
for (Integer intTemp : myInt) {
set.add(intTemp);
}

//TreeSet to String
//Iterator hasNext() and next()
Iterator iter = set.iterator();
while (iter.hasNext()) {
result += (Integer) iter.next() + " ";
}
return result;
}
}