Ok this is a tricky one. I have a list of Sets. I would like to sort the objects in the Sets in an order.
Imagine each set as repressenting a class in a school. Each
You must implement Comparable for your sortable objects (Person etc).
Then:
Setor
Examples:
import java.util.*;
class Person implements Comparable {
private String firstName, lastName;
public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName;}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getName() {return firstName + " " + lastName;}
public int compareTo(Person p) {
return lastName.compareTo(p.lastName);
}
}
class FirstNameComparator implements Comparator {
public int compare(Person p1, Person p2){
return p1.getFirstName().compareTo(p2.getFirstName());
}
}
class Test {
public static void log(String s) {
System.out.println(s);
}
public static void main(String[] args) {
Set people = new HashSet();
people.add(new Person("Bob", "Jones"));
people.add(new Person("Alice", "Yetti"));
log("Sorted list:");
List peopleList = new LinkedList();
peopleList.addAll(people);
Collections.sort(peopleList);
for (Person p : peopleList) {
log(p.getName());
}
log("TreeSet:");
TreeSet treeSet = new TreeSet();
treeSet.addAll(people);
for (Person p : treeSet) {
log(p.getName());
}
log("TreeSet (custom sort):");
TreeSet treeSet2 = new TreeSet(new FirstNameComparator());
treeSet2.addAll(people);
for (Person p : treeSet2) {
log(p.getName());
}
}
};