Either make the type itself implement Comparable
, implementing the compareTo
method by comparing the two strings, or implement a Comparator
which again compares by the strings.
With the first approach, you'd then just be able to use Collections.sort()
directly; with the second you'd use Collections.sort(collection, new FooComparator());
例えば:
public class Foo {
public String getBar() {
...
}
}
public class FooComparatorByBar implements Comparator {
public int compare(Foo x, Foo y) {
//TODO: Handle null values of x, y, x.getBar() and y.getBar(),
//and consider non-ordinal orderings.
return x.getBar().compareTo(y.getBar());
}
}