1600 PMP mock questions 1400 CAPM mock questions 800 SCJP 6 mock questions 600 OCAJP 7 mock questions 590 OCPJP 7 mock questions 556 SCWCD 5 mock questions 500 OCEJWCD 6 mock questions pdfDownload (java,struts, hibernet etc)

Java Tutorials

How to sort list of objects ( User Defined) using comparator?

You can use Collections.sort(List,Comparator) to sort objects.
Example : You have User Bean , you want to sort based on username filed.
User Class :
public class User {
String userName = "";
String city = "";
String state = "";
/**     * @return Returns the userName.
     */
    public String getUserName() {
        return userName;
    }
    /**
     * @param userName The userName to set.
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }
}

Then you have to write a comparator class.
public class UserNameComparator implements Comparator {
     public int compare(Object user, Object anotherUser) {
    
     String firstName1 = ((User) user).getUserName().toUpperCase();
    
     String firstName2 = ((User) anotherUser).getUserName().toUpperCase();
    
     return firstName1.compareTo(firstName2);
    
     }
    }

Now sorting code
User user1 = new User();
        user1.setUserName("das");
        User user2 = new User();
        user2.setUserName("nick");
        User user3 = new User();
        user3.setUserName("ram");
        User user4 = new User();
        user4.setUserName("jadu");
        
        ArrayList list = new ArrayList();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        
        Collections.sort(list,new UserNameComparator()); // sort ascending order.
        
        for(int i=0;i<list.size();i++){
            User usr = (User)list.get(i);
            System.out.println(usr.getUserName());
        }

Reviews and Comments


PMP, CAPM, PMI is a registered certification mark of the Project Management Institute, Inc

Copyright © www.techfaq360.com 2016


About US | Contact US | Privacy Policy | Terms and Conditions  | Website disclaimer  | Cancellation and Refund Policy  | Shipping & Delivery Policy