Java built in sort arraylist – Java Program to Sort an ArrayList

Java built in sort arraylist: In this article we will see how to sort an ArrayList in Java Programming language.

Java Program to Sort an ArrayList

We can sort the ArrayList by using 3 different ways as follows

Method-1: Java Program to Sort an ArrayList by Using Collections.sort() Method

Java built in sort arraylist: An ArrayList can be sorted by using the sort() method of the Collection class.

Parameter – Collection to be sorted

Returns – Sorted Collection in ascending order by default

Approach:

  • Declare an integer arraylist say evenNumber.
  • Add elements into arraylist.
  • Sort it by using inbuilt function Collections.sort(evenNumber);
  • Print the sorted ArrayList.

Program:

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

public class Main 
{
    public static void main(String[] args) 
    {
        //ArrayList of integers declared
        List<Integer> evenNumber = new ArrayList<>();
        //Elements added into ArrayList
        evenNumber.add(8);
        evenNumber.add(14);
        evenNumber.add(20);
        evenNumber.add(6);
        evenNumber.add(4);
        
        System.out.println("ArrayList before sorting : " + evenNumber);
        
        // Sorting an ArrayList using built-In method
        Collections.sort(evenNumber);
        System.out.println("ArrayList after sorting : " + evenNumber);
    }
}
Output:

ArrayList before sorting : [8, 14, 20, 6, 4]
ArrayList after sorting : [4, 6, 8, 14, 20]

Method-2: Java Program to Sort an ArrayList by Using ArrayList.sort() Method

An ArrayList can be sorted by using the sort() method by passing a Comparator.

Parameter

  1. List to be sorted based on the comparator.
  2. Comparator class instance

Returns – sorted in ascending order by default but does not return anything

Approach:

  • Declare an String arraylist say days.
  • Add elements into arraylist.
  • Sort it by using inbuilt function days.sort( );
  • Print the sorted ArrayList.

Program:

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

public class Main 
{

    public static void main(String[] args)
    {
        //ArrayList of String declared named as 'days'
        List<String> days = new ArrayList<>();
        //elements added
        days.add("Monday");
        days.add("Friday");
        days.add("Sunday");
        days.add("Thursday");
        
        System.out.println("Original Arraylist  : " + days);
        
        // Sort an ArrayList using its sort() method. 
        // Pass a Comparator to the ArrayList.sort() method.
        days.sort(new Comparator<String>() 
        {
            @Override
            public int compare(String day1, String day2) 
            {
                return day1.compareTo(day2);
            }
        });
        
        // sort() method written simply using lambda expression
        days.sort((day1, day2) -> day1.compareTo(day2));
        
        // Following is an even more concise solution
        days.sort(Comparator.naturalOrder());
        System.out.println("Sorted ArrayList: " + days);
    }
}
Output:

Original Arraylist : [Monday, Friday, Sunday, Thursday]
Sorted ArrayList: [Friday, Monday, Sunday, Thursday]

Method-3: Java Program to Sort an ArrayList by Using Custom Comparator

Approach:

  • Here, we’ve defined a UserDetails class with a String variable userName and Integer userID
  • We’ve also added a constructor that initializes the username and userId with getter and setter functions.
  • In the main() method, we’ve created an array list of users.
  • For sorting the list with the given property, we use the list‘s sort()
  • The sort() method takes the list to be sorted and a comparator.

Program:

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

// main class
public class Main 
{
    public static void main(String[] args) 
    {
        // declared a list of UserDetails
        List<UserDetails> users = new ArrayList<>();
        users.add(new UserDetails("Devika", 3));
        users.add(new UserDetails("Akash", 7));
        users.add(new UserDetails("Chitra", 4));
        users.add(new UserDetails("Barun", 1));
        
        System.out.println("Users Registered: " + users);
        
        // Sort users by their user-id
        users.sort((user1, user2) -> 
        {
        return user1.getUserID() - user2.getUserID();
        });
        
        
        // Sorting by using Collections.sort() method by passing the custom Comparator
        
        Collections.sort(users, Comparator.comparing(UserDetails::getUserName));
        System.out.println("Lexicographically Sorted Users List by UserName : " + users);
    }
}

class UserDetails
{
    // Private variables declared
    private String userName;
    private Integer userID;
    
    // constructor of UserDetails class
    public UserDetails(String userName, Integer userID) 
    {
    this.userName = userName;
    this.userID = userID;
    }
    
    // getter and setter methods to get access of private variables
    public String getUserName() 
    {
    return userName;
    }
    
    public void setUserName(String name) 
    {
    this.userName = userName;
    }
    
    public Integer getUserID() 
    {
    return userID;
    }
    
    public void setUserID(Integer age) 
    {
    this.userID = userID;
    }
    
    public String toString() 
    {
        return "{" +
        "User-Name ='" + userName + '\'' +",User-Id=" + userID +'}';
    }
}

Output:

Users Registered: [{User-Name ='Devika',User-Id=3}, {User-Name ='Akash',User-Id=7}, {User-Name ='Chitra',User-Id=4}, {User-Name ='Barun',User-Id=1}]
Lexicographically Sorted Users List by UserName : [{User-Name ='Akash',User-Id=7}, {User-Name ='Barun',User-Id=1}, {User-Name ='Chitra',User-Id=4}, {User-Name ='Devika',User-Id=3}]

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.