Jitendra Khedar
Jitendra Khedar

Reputation: 129

sorting a column manully through user interface

I am using hibernate to retrieving data from database. My UI shows different columns in table. I want to implement sorting functionality on the columns. this icon should be shown on column

On triggering the icon the name should be sorted like A-Z then Z-A.

please help me in this.

Upvotes: 0

Views: 60

Answers (1)

Debojit Saikia
Debojit Saikia

Reputation: 10632

You can sort your data by using a Comparator (assuming you don't want to hit the DB). Suppose you have a list of Category instances (categoryList) which is being displayed on your UI:

class Category{
private Long id;
private String categoryName;
private String otherProperty;
}

Now you can define custom strategies using Comparator interface to sort the Category instances present in your Category list:

class StartegyOne implements Comparator<Category> {

    @Override
    public int compare(Category c1, Categoryc2) {
        return c1.getCategoryName().compareTo(c2.getCategoryName());
    }

}

This StrategyOne will order Categories based on lexicographic ordering of their categoryNames; which can be achieved with Collections.sort:

Collections.sort(categoryList, AN_INSTANCE_OF_StrategyOne);

You can consider storing an instance of this Strategy class in a private static final field and reusing it:

/*This is the class that receives the sort action*/
class SortActionHandler{

private static final Comparator<Category> CATEGORY_ORDER = 
                                        new Comparator<Category>() {
            public int compare(Category c1, Categoryc2) {
                return c1.getCategoryName().compareTo(c2.getCategoryName());
            }
    };

//call this method to sort your list according to category names
private void sortList(List<Category> categoryList){
Collections.sort(categoryList, CATEGORY_ORDER);
}
}

Upvotes: 1

Related Questions