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?
Asked
Active
Viewed 3,149 times
0
-
2Possible duplicate of: http://stackoverflow.com/questions/3342517/sorting-arraylist-of-objects-by-object-attribute – Kris Feb 06 '12 at 12:07
3 Answers
4
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());
}
}

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
1
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);
}
}

rlegendi
- 10,466
- 3
- 38
- 50
0
Using Guava, it's just
Collections.sort(list, Ordering.natural().compose(Functions.toStringFunction()));

Louis Wasserman
- 191,574
- 25
- 345
- 413