import java.io.File; import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.Comparator; import java.util.Collections; import java.io.IOException; import java.util.Scanner; /** * COP3337 Example * * @author Bill Kraynek */ public class ComparatorExample { public static void main(String[] args) throws IOException { ArrayList people = new ArrayList<>(); Scanner fileScanner = new Scanner(new File("people.data")); while (fileScanner.hasNext()) { Scanner s = new Scanner(fileScanner.nextLine()); String idNumber = s.next(); String first = s.next(); String last = ""; while (s.hasNext()) { last += s.next() + " "; } // end while if (!last.equals("")) { last = last.substring(0, last.length() - 1); } // end if Person aPerson = new Person(idNumber, first, last); // add aPerson to the end of the ArrayList people.add(aPerson); } // end while // The Collections class has a static method sort. // sort takes an ArrayList paramenter // The objects in the ArrayList must be Comparable // The ArrayList is sorted according to the natural comparator Collections.sort(people); display(people, "The names in \"natural\" order are:\n"); // The Collections class has a second static method sort. // This sort takes an ArrayList paramenter and a Comparator parameter // The ArrayList is sorted according to the Comparator Collections.sort(people, new NameLengthOrder()); display(people, "The names in first name length order are:\n"); Collections.sort(people, new Person.idNumberOrder()); display(people, "The names in idNumber order are:\n"); } // end main public static void display(ArrayList a, String title) { String out = title + "\n"; for (int i = 0; i < a.size(); i++) { // the toString() method is automatically called on // a.get(i) since we are concatenating to a String // the "correct" toString() method is called // because of polymorphism out += a.get(i) + "\n"; } // end for JOptionPane.showMessageDialog(null, out); } // end display // Comparator is an interface with one method to implement, the compare method. // This class implements compare so the order is by first name length. static class NameLengthOrder implements Comparator { public int compare(Person personA, Person personB) { int lengthA = personA.getFirstName().length() + personA.getLastName().length(); int lengthB = personB.getFirstName().length() + personB.getLastName().length(); int difference = lengthB - lengthA; if (difference != 0) { return difference; } // if no difference in name length compare "naturally" return personA.compareTo((personB)); } // end compare } // end NameLengthOrder } // end ComparatorExample