import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * * @author Bill Kraynek */ public class SetExample { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Scanner fileScanner = new Scanner(new File("src/SetExample.java")); fileScanner.useDelimiter("[^a-zA-Z]+"); Set words = new HashSet(); Set sortedWords = new TreeSet(); while( fileScanner.hasNext() ) { String word = fileScanner.next(); words.add(word); sortedWords.add(word); }// end while String wordsOut = toString(words); JTextArea outArea = new JTextArea(wordsOut,50,20); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); String sortedWordsOut = toString(sortedWords); outArea.setText(sortedWordsOut); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); Set lengthSortedWords = new TreeSet(new LengthComparator()); lengthSortedWords.addAll(words); String lengthSortedWordsOut = toString(lengthSortedWords); outArea.setText(lengthSortedWordsOut); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); } static String toString(Set set) { String out = ""; Iterator itr = set.iterator(); while( itr.hasNext() ) { out += itr.next() + "\n"; }// end while return out; } static class LengthComparator implements Comparator { public int compare(String lhs, String rhs) { int lengthDiff = rhs.length() - lhs.length(); if( lengthDiff == 0 ) return lhs.compareTo(rhs); return lengthDiff; }// end comparte }// end lengthComparator }