import java.io.*; import java.util.*; import javax.swing.*; /** * This Example illustrates a SortedLinkedList class * @author Bill Kraynek */ public class SortedLinkedListExample { public SortedLinkedListExample() { try{ BufferedReader in = new BufferedReader(new FileReader("SortedLinkedListExample.java")); String file = ""; final String DELIMITERS = " :;,&$%@^[]?_#{}|().+-/*=<>!\t\n\r\'\"\\"; String aLine; while( (aLine = in.readLine()) != null ) { StringTokenizer parser = new StringTokenizer(aLine,DELIMITERS); while( parser.hasMoreTokens() ) { file += parser.nextToken() + " "; } // end while } // end while List words = getWordsSorted(file); displayList(words); words = getWordsSortedIgnoreCase(file); displayList(words); } catch(Exception e) { System.out.println(e); } } /** * Parse the String file for 'words' and store unique words in the List words * in sorted order * @param file is the String @ @return the List of sorted words */ public List getWordsSorted(String file) { List words = new SortedLinkedList(); StringTokenizer parser = new StringTokenizer(file); while( parser.hasMoreTokens() ) { String nextWord = parser.nextToken(); if( !words.contains(nextWord) ) { words.add(nextWord); } // end if } // end while return words; } // end getWordsSorted /** * Parse the String file for 'words' and store unique words (ignoring case) * in the List words in sorted order ignoring case * @param file is the String @ @return the List of sorted words */ public List getWordsSortedIgnoreCase(String file) { List words = new SortedLinkedList(new IgnoreCaseComparator()); StringTokenizer parser = new StringTokenizer(file); while( parser.hasMoreTokens() ) { String nextWord = parser.nextToken(); if( !words.contains(nextWord) ) { words.add(nextWord); } // end if } // end while return words; } // end getWordsSortedIgnoreCase /** * Display a List in a JTextArea * @param l is the List to display */ public void displayList(List aList) { Iterator itr = aList.iterator(); String out = ""; while( itr.hasNext() ) { out += " " + itr.next() + "\n"; } JTextArea outArea = new JTextArea(25,40); outArea.setText(out); JOptionPane.showMessageDialog(null,new JScrollPane(outArea)); } private class IgnoreCaseComparator implements Comparator { public int compare(Object a, Object b) { return ((String)a).compareToIgnoreCase((String)b); } } public static void main(String args[]) throws IOException { new SortedLinkedListExample(); System.exit(0); } // end main } // end SortedLinkedListExample