Custom comparator in Java

Hi friends,

Let’s look into the code how to make a custom comparator that sorts a list, according to the field we pass, as a parameter. Both the field and the list are passed as parameters.

Initially, we create two comparators – one for sorting the list by “id” field and another for sorting by “name” field.

Next, we write a static sort method, which accepts a list and a field of type String. The logic inside this method decides how to sort the list.

Let’s move onto a sample code. Actually I’ve found this logic on another website while i was digging on internet.


import crit.pojo.UtilPojo;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CustomComparator {

    private static Comparator<UtilPojo> idComparator = new Comparator<UtilPojo>() {

        public int compare(final UtilPojo pojo1, final UtilPojo pojo2) {
            return Long.valueOf(pojo1.getId()).compareTo(Long.valueOf(pojo2.getId()));
        }
    };
    private static Comparator<UtilPojo> nameComparator = new Comparator<UtilPojo>() {

        public int compare(final UtilPojo pojo1, final UtilPojo pojo2) {
            return pojo1.getName().compareTo(pojo2.getName());
        }
    };

    public static List<UtilPojo> sort(final List<UtilPojo> list, final String field) throws Exception {
        try {
            final Comparator<UtilPojo> comparator;
            if (field.equals("id")) {
                comparator = idComparator;
            } else if (field.equals("name")) {
                comparator = nameComparator;
            } else {
                throw new IllegalArgumentException("Comparator not found for the field, " + field);
            }
            Collections.sort(list, comparator);
            return list;

        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
}

The POJO, type of the list created is given below.

public class UtilPojo {

    private String name;
    private long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public UtilPojo(long id, String name) {
        this.id = id;
        this.name = name;
    }

    public UtilPojo() {
    }
}

Let’s see an example using this “Custom Comparator” in the next post.

Thanks.

Published by

Deepesh Darshan K R

I am Me. In all the world, there is no one else exactly like me. Everything that comes out of me is authentically mine, because I alone chose it. I own everything about me: my body, my feelings, my mouth, my voice, all my actions, whether they be to others or myself. I own my fantasies, my dreams, my hopes, my fears. I own my triumphs and successes, all my failures and mistakes. Because I own all of me, I can become intimately acquainted with me. By so doing, I can love me and be friendly with all my parts. I know there are aspects about myself that puzzle me, and other aspects that I do not know -- but as long as I am friendly and loving to myself, I can courageously and hopefully look for solutions to the puzzles and ways to find out more about me. However I look and sound, whatever I say and do, and whatever I think and feel at a given moment in time is authentically me. If later some parts of how I looked, sounded, thought, and felt turn out to be unfitting, I can discard that which is unfitting, keep the rest, and invent something new for that which I discarded. I can see, hear, feel, think, say, and do. I have the tools to survive, to be close to others, to be productive, and to make sense and order out of the world of people and things outside of me. I own me, and therefore, I can engineer me. I am me, and . . . . . . . . . . I am Okay. Haha.. Let it go.. I am a software engineer working in a MNC here at Kochi itself, specialized on J2EE platform, dribbling with frameworks like struts, hibernate etc.

2 thoughts on “Custom comparator in Java”

Leave a comment