0

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?

1

3 Answers 3

5

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());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Should that be Comparator rather than Comparer?
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);
    }
}

Comments

0

Using Guava, it's just

Collections.sort(list, Ordering.natural().compose(Functions.toStringFunction()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.