Skip to main content

Sort ArrayList in Java

How to sort ArrayList in Java

In this article, we are going to learn how we can sort ArrayList in Java. ArrayList is one of the most important classes of Java and it is a part of the Java Collection Framework. To sort Arraylist in Java, first we should understand what is ArrayList in Java.
There is a number of ways to sort ArrayList in Java and it is very hard to incorporate all of those methods in a single post. So, we are going to learn the most common approaches to sort ArrayList in Java.
To have a basic idea of how we can sort ArrayList in Java, let's look at the very simple example to sort ArrayList in Java.

ArrayList Sort Example 1 : Create a list of strings and sort in ascending order

ArrayList<String> books = new ArrayList<>();
books.add("Programming in Java");
books.add("Let's Start JavaScript");
books.add("Data Structures");
books.add("Introduction to Algorithms");
books.add("Concept of Databases");

Collections.sort(books);

books.forEach(bookName -> System.out.println(bookName));
Output
Concept of Databases
Data Structures
Introduction to Algorithms
Let's Start JavaScript
Programming in Java
As we can see, the book's names are sorted into alphabetically ascending order. Here, we have used Collections.sort() method to sort ArrayList in Java which sort the ArrayList in ascending order. Let's take another example to sort Arraylist in java.

ArrayList Sort Example 2 : Create a list of integer and sort in ascending order

ArrayList<Integer> integers = new ArrayList<>();
integers.add(54);
integers.add(23);
integers.add(78);
integers.add(12);
integers.add(7);
Collections.sort(integers);
System.out.println(integers);
Output
[7, 12, 23, 54, 78]
Here we have used Collections.sort() method again to sort List of Integers.

What is Collections.sort() method?

The Collections is a utility class which is defined into the java.util package and provides lots of static methods. One of the static method of Collections class is sort() method which sort the ArrayList in ascending order.
The Collections.sort() method takes an argument of List<T>, here T is the type of ArrayList and T must be child of Comparable interface i.e., any ArrayList whose type is child of Comparable Interface can be sort using this method.
In the above examples, String and Integer both are the child of Comparable Interface. So both the created ArrayList is applicable for sorting using Collections.sort() method.

How to sort ArrayList in Java of Custom Objects using Comparable?

Before understanding How to sort ArrayList in Java of Custom Objects using Comparable?, lets first look at What is Comparable Interface.

What is Comparable Interface?

Comparable interface is an interface which is used to ordering the objects, if the class of that object implements this interface. This ordering is known as Natural Ordering. It is done by using compareTo() method.
Definition of Comparable Interface
interface Comparable<T> {
       public int compareTo(T o);
}

Any class, who wants to order it objects, need to implements this interface and provide definition of compareTo() method.
and object one can compare object two by invoking compareTo() method as obj1.compareTo(obj2). If the compareTo() returns :
  • A positive integer i.e., obj1.compareTo(obj2) > 0; signifies that obj1 object is greater than obj2.
  • A negative integer i.e., obj1.compareTo(obj2) < 0; signifies that obj1 object is smaller than obj2.
  • And Zero i.e., obj1.compareTo(obj2) == 0; signifies that obj1 object is equals to the argument obj2.
As we know now, to sort the list of custom objects, the class of custom objects needs to implement Comparable Interface and provide the definition of compareTo() method. Let's model a custom class and implements the Comparable Interface.
class Book implements Comparable<Book> {
     private String name;
     private int price;

     public Book(String name, int price){
          this.name = name;
          this.price = price;
     }

     public String getName() {
          return name;
     }

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

     public int getPrice() {
          return price;
     }

     public void setPrice(int price) {
          this.price = price;
     }

     @Override
     public String toString(){  
          return "[ " + name + " : " + price + " ]";
     }

     @Override
     public int compareTo(Book o) {
          return this.price - o.getPrice();
     }   
}
Now, this Book class has its own definition of compareTo() method on the basis of the "price" value of the Book. As Book class implemented Comparable Interface so that ArrayList of Book class can be sorted using Collections.sort() method.
Create a list of books
ArrayList<Book> books = new ArrayList<>();
books.add(new Book("Programming in Java" , 450));
books.add(new Book("Let's Start JavaScript" , 300));
books.add(new Book("Data Structures" , 650));
books.add(new Book("Introduction to Algorithms" , 400));
books.add(new Book("Concept of Databases" , 500));

ArrayList Sort Example 3 : Sort ArrayList in java in ascending order w.r.t. price

System.out.println("-----List of Books Before : Sorting---------");
books.forEach(book -> System.out.println(book));

Collections.sort(books);

System.out.println("-----List of Books After : Sorting----------");
books.forEach(book -> System.out.println(book));
Output
-----List of Books Before : Sorting---------
[ Programming in Java : 450 ]
[ Let's Start JavaScript : 300 ]
[ Data Structures : 650 ]
[ Introduction to Algorithms : 400 ]
[ Concept of Databases : 500 ]
-----List of Books After : Sorting----------
[ Let's Start JavaScript : 300 ]
[ Introduction to Algorithms : 400 ]
[ Programming in Java : 450 ]
[ Concept of Databases : 500 ]
[ Data Structures : 650 ]
As we can see, the list has been sorted in ascending order w.r.t. "price" of the book. But what we need to do if we want to sort the list in terms of the "name" of the book. So that we need to change the definition of compareTo() method provided by the Book class.
class Book implements Comparable<Book> {
     ------------------
     ------------------
     ------------------


     @Override
     public int compareTo(Book o) {
          return this.name.compareTo(o.getName());
     }   
}

ArrayList Sort Example 4 : Sort ArrayList in java in ascending order w.r.t. name

System.out.println("-----List of Books Before : Sorting---------");
books.forEach(book -> System.out.println(book));

Collections.sort(books);

System.out.println("-----List of Books After : Sorting----------");
books.forEach(book -> System.out.println(book));
Output
-----List of Books Before : Sorting---------
[ Programming in Java : 450 ]
[ Let's Start JavaScript : 300 ]
[ Data Structures : 650 ]
[ Introduction to Algorithms : 400 ]
[ Concept of Databases : 500 ]
-----List of Books After : Sorting----------
[ Concept of Databases : 500 ]
[ Data Structures : 650 ]
[ Introduction to Algorithms : 400 ]
[ Let's Start JavaScript : 300 ]
[ Programming in Java : 450 ]
Now the ArrayList is sorted according to the "name of the book". But this is not the right approach to change the definition of compareTo() method each time whenever we want to sort ArrayList in Java in different terms then the Comparable Interface is not the right approach. The alternative for Comparable Interface is the Comparator<T> interface

How to sort ArrayList in Java using Comparator?

The Collections utility class provides an overloaded method of sort() method as
Overloaded Collections.sort() method
void sort(List<T> list, Comparator<T> comparator);
This overloaded method takes two arguments, one is the List<T> and another is the Comparator<T>, both must be of the same type. Comparator<T> argument is used to provide custom logic to sort ArrayList in Java. When we use this method to sort ArrayList in Java, Objects of the ArrayList don't need to be children of Comparable Interface. Now, lets first understand what is Comparator interface and how we can create an instance of it.

What is Comparator interface?

Comparator Interface is a Functional Interface which is used to write custom logic to sort ArrayList in Java. This interface provides an abstract method named as compare(T o1, T o2) which takes two argument, both of same type, and compare each other.
Definition of Comparator Interface
interface Comparator<T> {
       public int compare(T o1, T o2);
}
To sort ArrayList in Java using Comparator, we need to provide definition of compare(o1, o2) method. The definition must follow below mentioned criteria that, If the compare(o1, o2) method returns :
  • A positive integer i.e., compare(o1, o2) > 0; signifies that o1 object is greater than o2.
  • A negative integer i.e., compare(o1, o2) < 0; signifies that o1 object is smaller than o2.
  • And Zero i.e., compare(o1, o2) == 0; signifies that o1 object is equals to the argument o2.

How we can instantiate Comparator interface?

To create an object of Comparator, we have two approach one is using Anonymous class and another is using Lambda Expression in Java. Let look at both of them
Instantiate Comparator Interface using Anonymous class
Comparator<String> stringComparator = new Comparator<String>() { 
         @Override
         public int compare(String o1, String o2) {
                  return o1.compareTo(o2);
         }
};
Instantiate Comparator Interface using Lambda Expression In Java
Comparator<String> stringComparator = (o1, o2) -> o1.compareTo(o2);
It is very easy to instantiate Comparator using Lambda Expression instead of Anonymous class but Lambda expression is introduced in Java 8. Read this article to know more about Lambda Expression In Java. So, if you are using any prior version of Java then the Anonymous class is a good option to create the object of Comparators.

Sort ArrayList in Java using Comparators

Above we have seen how we can write Comparators to provide custom logic for sorting an ArrayList. Now let's have a look at an example to sort ArrayList in Java using comparators.

ArrayList Sort Example 5 : Sort the previously created ArrayList which is "books" in ascending order first w.r.t. to "price" and then w.r.t. "name" by using Comparators to provide custom logic to sort ArrayList in Java

System.out.println("-----List of Books Before : Sorting---------");
books.forEach(book -> System.out.println(book));

// Sort books w.r.t. Price
Comparator<Book> priceComparator = (o1, o2) -> o1.getPrice() - o2.getPrice();
Collections.sort(books, priceComparator);
System.out.println("\n-----List of Books After : Sorting w.r.t. Price----------");
books.forEach(book -> System.out.println(book));

// Sort books w.r.t. Name
Comparator<Book> nameComparator = (o1, o2) -> o1.getName().compareTo(o2.getName());
Collections.sort(books, nameComparator);
System.out.println("\n-----List of Books After : Sorting w.r.t. Name----------");
books.forEach(book -> System.out.println(book));
Output
-----List of Books Before : Sorting---------
[ Programming in Java : 450 ]
[ Let's Start JavaScript : 300 ]
[ Data Structures : 650 ]
[ Introduction to Algorithms : 400 ]
[ Concept of Databases : 500 ]

-----List of Books After : Sorting w.r.t. Price----------
[ Let's Start JavaScript : 300 ]
[ Introduction to Algorithms : 400 ]
[ Programming in Java : 450 ]
[ Concept of Databases : 500 ]
[ Data Structures : 650 ]

-----List of Books After : Sorting w.r.t. Name----------
[ Concept of Databases : 500 ]
[ Data Structures : 650 ]
[ Introduction to Algorithms : 400 ]
[ Let's Start JavaScript : 300 ]
[ Programming in Java : 450 ]

How to sort ArrayList in Java in Reverse or Descending order?

Till now we know how to sort ArrayList in Java in ascending order, now its time to see how to sort ArrayList in Java in descending order. To do this, Collections class provides a method Collections.reverseOrder().
Lets first look at the syntax of this method.
Collections.reverseOrder() method
Comparator<T> reverseOrder(Comparator<T> c);
As we can see, Collections.reverseOrder() takes an argument of Comparator<T> and returns a Comparator<T>. The returned Comparator provides the reverse ordering of the specified argumented Comparator.

ArrayList Sort Example 6 : Sort the "books" named ArrayList in reverse order first w.r.t. to "price" and then w.r.t. "name"

System.out.println("-----List of Books Before : Sorting---------");
books.forEach(book -> System.out.println(book));

// Sort books w.r.t. Price
Comparator<Book> priceComparator = (o1, o2) -> o1.getPrice() - o2.getPrice();
Collections.sort(books, Collections.reverseOrder(priceComparator));
System.out.println("\n-----List of Books After : Sorting in descending w.r.t. Price----------");
books.forEach(book -> System.out.println(book));

// Sort books w.r.t. Name
Comparator<Book> nameComparator = (o1, o2) -> o1.getName().compareTo(o2.getName());
Collections.sort(books, Collections.reverseOrder(nameComparator));
System.out.println("\n-----List of Books After : Sorting in descending w.r.t. Name----------");
books.forEach(book -> System.out.println(book));
Output
-----List of Books Before : Sorting---------
[ Concept of Databases : 500 ]
[ Data Structures : 650 ]
[ Introduction to Algorithms : 400 ]
[ Let's Start JavaScript : 300 ]
[ Programming in Java : 450 ]

-----List of Books After : Sorting in descending w.r.t. Price----------
[ Data Structures : 650 ]
[ Concept of Databases : 500 ]
[ Programming in Java : 450 ]
[ Introduction to Algorithms : 400 ]
[ Let's Start JavaScript : 300 ]

-----List of Books After : Sorting in descending w.r.t. Name----------
[ Programming in Java : 450 ]
[ Let's Start JavaScript : 300 ]
[ Introduction to Algorithms : 400 ]
[ Data Structures : 650 ]
[ Concept of Databases : 500 ]

Related Posts:


Conclusion

In this article, we have learnt how to sort ArrayList in Java using Comparable. Also, we have seen how we can provide custom logic to sort ArrayList in Java using Comparators. And lastly, we concluded with sorting in reverse or descending order an ArrayList.

Comments

  1. As we know there are many companies which are converting into Big data app development. with the right direction we can definitely predict the future.

    ReplyDelete

Post a Comment

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…