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.
i’ve read this before, but still interesting.
i have heard this before but can’t recall where i did, still interesting though,