Monday, September 22, 2014

Inline Comparator Example

Here's an example of using an inline comparator in java.

To sort a list of Person objects according to its 'name' property, use the template below.

List personList = personListDTO.getPersons();
Collections.sort(personList ,new Comparator() {
   public int compare(Object o1, Object o2) {
    Person p1 = (Person)o1;
    Person p2 = (Person)o2;
    return p1.getName().compareTo(p2.getName());

You may also use the more compact form below.

List<Person> personList = personListDTO.getPersons(); 
Collections.sort(personList ,new Comparator<Person>() {
 public int compare(Person p1, Person p2) {
  return p1.getName().compareTo(p2.getName());

This code will help you avoid getting a warning in eclipse of the generic type -

- Type safety: The expression of type new Comparator(){} needs unchecked conversion to conform to Comparator<? super Person>
- Type safety: Unchecked invocation sort(List<Person>, new Comparator(){}) of the generic method sort(List<T>, Comparator<? super T>) of type Collections
- Comparator is a raw type. References to generic type Comparator<T> should be parameterized 

Related Links:
More examples on using Comaparator in Java
How to sort a map in Java

Collections class reference

Decode HTML Entities

This post is nothing special. Just a note to myself.

I needed a basic javascript function to decode HTML entities in a string. The string that is retrieved from the database was being encoded in the jsp with the HTML entity '&amp;' encoded in the string. 

So the string 'Tom & Harry' is being shown as "Tom &amp; Harry'.

I wrote a basic HTML decoder function in javascript since the strings are coming from a trusted source (my database).

Here is the HTML decoder function.

function decodeHTMLEntities(str) {
 var textArea = document.createElement("textarea");
 textArea.innerHTML = str; 
 return textArea.value;

If the source of the data is not trusted, you may use some of the other HTML decoder options discussed in the following links.

HTML decode options 1
HTML decode options 2

Please take note that the discussions from these links advise against using jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM.

HTML Entity Reference
HTML Entitiy Reference