Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to sort ArrayList in Java?

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 503
    Comment on it

    Sometimes we want to sort a List based on some property. Suppose we have a List of UserModel and we want to sort List by firstName then we can do that easily by using Collections.sort() and Comparator interface.

    Example: In the below example I'm sorting userList by firstName.

    1. First you nee to create a Model class on which you want to apply sorting.

    UserModel.java

    public class UserModel
    {
        private int userId;
        private String firstName;
        private String lastName;
        private String email;
       
        public int getUserId()
        {
            return userId;
        }
    
        public void setUserId(int userId)
        {
            this.userId = userId;
        }
    
        public String getFirstName()
        {
            return firstName;
        }
    
        public void setFirstName(String firstName)
        {
            this.firstName = firstName;
        }
    
        public String getLastName()
        {
            return lastName;
        }
    
        public void setLastName(String lastName)
        {
            this.lastName = lastName;
        }
    
        public String getEmail()
        {
            return email;
        }
    
        public void setEmail(String email)
        {
            this.email = email;
        }
    }


    2. Now create Comparator class as below

        /**
         * Comparator class to compare users by firstName
         */
        public static class UserModelComparator implements Comparator<UserModel> {
            @Override
            public int compare(UserModel o1, UserModel o2)
            {
                return (int) (o1.getFirstName().toLowerCase().compareTo(o2.getFirstName().toLowerCase()));
            }
        }

    3. Now create sort function and pass List into that function as below


      

        public static List<UserModel> getSortedListByFirstName(List<UserModel> userModels)
        {
            Collections.sort(userModels, new UserModelComparator());
            return userModels;
        }

    the above function will return sorted list by firstName.

    Hope this will help you :)

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: