import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; 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 * * COP3337 Example */ public class SetsExample { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Set words = new HashSet<>(); Set sortedWords = new TreeSet<>(); Set sortedIgnoreCaseWords = new TreeSet<>(new IgnoreCaseComparator()); Set sortedLengthWords = new TreeSet<>(new StringLengthComparator()); Scanner scanner = new Scanner(new File("src/SetsExample.java")); scanner.useDelimiter("[^a-zA-Z]+"); while( scanner.hasNext() ) { String aWord = scanner.next(); words.add(aWord); sortedWords.add(aWord); sortedIgnoreCaseWords.add(aWord); sortedLengthWords.add(aWord); }// end while display(words); display(sortedWords); display(sortedIgnoreCaseWords); display(sortedLengthWords); } public static void display(Collection collection) { String out = ""; for( T x : collection) { out += x + "\n"; }// end for out += "\n"; JOptionPane.showMessageDialog(null,new JScrollPane(new JTextArea(out,30,30))); } static class IgnoreCaseComparator implements Comparator { public int compare(String lhs, String rhs) { return lhs.compareToIgnoreCase(rhs); } } static class StringLengthComparator implements Comparator { public int compare(String lhs, String rhs) { int diff = rhs.length() - lhs.length(); if( diff != 0 ) return diff; return lhs.compareToIgnoreCase(rhs); } } }