Sunday, 10 July 2016

Sorting List of Beans in Java

If we have list of beans and if we want to sort the list based on bean property, we can use the bellow code.

Collections.sort(beans, new Comparator() { 
@Override 
public int compare(SortingBean o1, SortingBean o2) {
          return o1.getName().compareTo(o1.getName()); 

}); 

Example:

package com.sample.java.testing;

public class SortingBean {

    private int id;
    private String name;
    private String role;


    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}
 

Sorting  code:

package com.sample.java.testing;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class BeanSortExample {

    public static void main(String[] args) {
        /**
         * Just as an example, creating the beans and added into the list. But
         * generally , we will get these results from database or from some other
         * source. Then if we need any sorting the list, then we can use below
         * code.
         */

        List<SortingBean> beans = new ArrayList<SortingBean>();
        SortingBean bean = new SortingBean();
        bean.setId(200);
        bean.setName("jklmn");
        bean.setRole("TA");
        SortingBean bean1 = new SortingBean();
        bean1.setId(101);
        bean1.setName("abcde");
        bean1.setRole("TA");
        SortingBean bean3 = new SortingBean();
        bean3.setId(203);
        bean3.setName("zxyv");
        bean3.setRole("TA");
        beans.add(bean);
        beans.add(bean1);
        beans.add(bean3);
        System.out.println("before sort....");
        for (SortingBean unSortingBean : beans) {
            System.out.println("list of employee ids... " + unSortingBean.getId());
        }

        /**
         * Below lines of code will sort the list of beans based on the id property.
         */

        Collections.sort(beans, new Comparator<SortingBean>() {

            @Override
            public int compare(SortingBean o1, SortingBean o2) {
               return Integer.compare(o1.getId(), o2.getId());
            }
        });
        System.out.println("after sort....");
        for (SortingBean sortingBean : beans) {
            System.out.println("list of employee ids... " + sortingBean.getId());
        }
    }
}