I have Java bean class and I want to sort list of these beans by one bean attribute that is of String type. How can I do that?
3 Answers
Either make the type itself implement Comparable<Foo>, implementing the compareTo method by comparing the two strings, or implement a Comparator<Foo> 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());
For example:
public class Foo {
public String getBar() {
...
}
}
public class FooComparatorByBar implements Comparator<Foo> {
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());
}
}
1 Comment
Mark Pope
Should that be Comparator rather than Comparer?
By using a custom Comparator?
import java.util.*;
class Bean {
public final String name;
public final int value;
public Bean(final String name, final int value) {
this.name = name;
this.value = value;
}
@Override
public String toString() {
return name + " = " + value;
}
}
public class SortByProp {
private static List<Bean> initBeans() {
return new ArrayList<Bean>(Arrays.asList(
new Bean("C", 1),
new Bean("B", 2),
new Bean("A", 3)
));
}
private static void sortBeans(List<Bean> beans) {
Collections.sort(beans, new Comparator<Bean>() {
public int compare(Bean lhs, Bean rhs){
return lhs.name.compareTo(rhs.name);
}
});
}
public static void main(String[] args) {
List<Bean> beans = initBeans();
sortBeans(beans);
System.out.println(beans);
}
}
Comments
Using Guava, it's just
Collections.sort(list, Ordering.natural().compose(Functions.toStringFunction()));