[FIXED] How to sort a collection based on java.lang.reflect.Field?


I’m stuck in a situation where I only got Fields (java.lang.reflect) of a given class.

To help you better imagine, let’s say we have code:

List<Apple> sortApplesByFieldName(List<Apple> apples, String fieldName) {
    Field field = Apple.class.getDeclaredField(fieldName);

    // some stream logic for sorting using this var
    return apples;

Can someone actually solve this problem?

Also, using a switch statement is not an option, as fields can change.

Note, the class Apple is a regular POJO with private fields and public getters/setters.


Something like this. It will throw a ClassCastException if the field can’t be compared.

Bit ugly, but isn’t reflection always.

<T extends Comparable<T>> List<Apple> sortApplesByFieldName(List<Apple> apples, String fieldName)
        throws NoSuchFieldException {
    Field field = Apple.class.getDeclaredField(fieldName);

    return apples.stream()
        .sorted(Comparator.comparing(apple -> {
            try {
                return (T) field.get(apple);
            catch (IllegalAccessException e) {
                throw new RuntimeException(e);

Answered By – Michael

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published