Responsive Ads Here

Friday, March 6, 2020

How to sort arraylist in java [Arraylist sorting best solutions]

How to sort ArrayList in java ??

When we work around ArrayList in java we have to perform multiple operations on ArrayList, among them sorting ArrayList is most frequently used operation.

So let's try to sort ArrayList in different way in using java .

How to sort ArrayList in java


Method 1, How  to sort arraylist in java for String.
There is a utility class called Collections. It has sort(T) method that can sort your list. The signature of the sort method used is as :

Collections.sort(List<T> list); 

## This will sort the specified list into ascending order, according to comparable natural ordering. 

## All element in the list must implement Comparable interface

## All element in the list must be mutually comparable, that means compareTo(e)  method must not throw a ClassCastException for any element in the list.

## This sort is guaranteed to be stable, equal elements will not be reordered as a result of the sort.

## The specified list must be modifiable. 

Example :
public class SortDemo {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Santosh", "Raj", "Naveen", "Ritvik", "Sumant", "Vaibav", "Arjun");
        // I have a names list going to sort the same.
        Collections.sort(names);
        System.out.println(names);
    }
}

Output :

[Arjun, Naveen, Raj, Ritvik, Santosh, Sumant, Vaibav]

You can see the given output it has been sorted according to default sorting order.

We can used java 8 lambda expression to sort the list as
public class SortDemo {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Santosh", "Raj", "Naveen", "Ritvik", "Sumant", "Vaibav", "Arjun");
        // Sorting the list using lemda java 8
        // how to sort arraylist in java
        names = names.stream().sorted().collect(Collectors.toList());
        System.out.println(names);
    }
}

Output will be same as above

[Arjun, Naveen, Raj, Ritvik, Santosh, Sumant, Vaibav]

Note : If you want to sort your list in descending order your can do so by using Comparator interface as given in example.

In java 8 using lemda
public class SortDemo {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Santosh", "Raj", "Naveen", "Ritvik", "Sumant", "Vaibav", "Arjun");
        // Sorting the list using lemda java 8
        // how to sort arraylist in java
        names = names.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        System.out.println(names);
    }
}
Output :
[Vaibav, Sumant, Santosh,, Ritvik, Raj, Naveen, Arjun]

Descending order using Collections
public class SortDemo {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Santosh", "Raj", "Naveen", "Ritvik", "Sumant", "Vaibav", "Arjun");
        // Sorting the list using Collections java 
        Collections.sort(names, Collections.reverseOrder());
        System.out.println(names);
    }
}

Output :
[Vaibav, Sumant, Santosh, Ritvik, Raj, Naveen, Arjun]



Method 2, To Sort ArrayList in java for Custom Object.

 Example 1.  Sort the List of custom object

Let suppose we have Student.java class with properties as rollNo, name, address and we want to sort the student on name.

package blog.scjp;

public class Student implements Comparable<Student>{
 private Integer rollNo;
 private String name;
 private String address;
 
 public Student() {
 }
 
 public Student(Integer rollNo, String name, String address) {
  super();
  this.rollNo = rollNo;
  this.name = name;
  this.address = address;
 }
 public Integer getRollNo() {
  return rollNo;
 }
 public void setRollNo(Integer rollNo) {
  this.rollNo = rollNo;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }

 @Override
 public String toString() {
  return "Student [rollNo=" + rollNo + ", name=" + name + ", address=" + address + "]";
 }

 @Override
 public int compareTo(Student o) {
  //for Ascending order
  return this.getName().compareTo(o.getName());
  //for descending order
  //return o.getName().compareTo(this.getName());
 }
 
}

This is the class that implement comparable so we have to implements compareTo(T) method. I have written logic to sort the student on the basis of name ascending or descending.

package blog.scjp;

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

public class MainTestBlog {

 public static void main(String[] args) {
  Student student1 = new Student(1, "Santosh", "Noida");
  Student student2 = new Student(3, "Amit", "GZB");
  Student student3 = new Student(2, "Naman", "Delhi");
  Student student4 = new Student(4, "Raj", "Greater Noida");
  Student student5 = new Student(5, "Rajesh", "Delhi");
  Student student6 = new Student(1, "Naveen", "Patna");

  List<Student> students = new ArrayList<Student>();
  students.add(student1);
  students.add(student2);
  students.add(student3);
  students.add(student4);
  students.add(student5);
  students.add(student6);

  System.out.println("Before Sorting");
  System.out.println(students);
  Collections.sort(students);
  System.out.println("After Sorting");
  System.out.println(students);
 }

}

Output of this program
For ascending order sorting :

Before Sorting
[Student [rollNo=1, name=Santosh, address=Noida], Student [rollNo=3, name=Amit, address=GZB], Student [rollNo=2, name=Naman, address=Delhi], Student [rollNo=4, name=Raj, address=Greater Noida], Student [rollNo=5, name=Rajesh, address=Delhi], Student [rollNo=1, name=Naveen, address=Patna]]
After Sorting
[Student [rollNo=3, name=Amit, address=GZB], Student [rollNo=2, name=Naman, address=Delhi], Student [rollNo=1, name=Naveen, address=Patna], Student [rollNo=4, name=Raj, address=Greater Noida], Student [rollNo=5, name=Rajesh, address=Delhi], Student [rollNo=1, name=Santosh, address=Noida]]

According to output we can see ArrayList has been sorted based on object attributed name, added into the list.




Example 2.  Sort the List of custom object

We may need to sort the list of Student which does not implements Comparable interface. In that case we can use Comparable interface.

## In case of Comparable, Student class does not have to implements any interface.

## If we want to sort the list of object using Comparator we have to use overloaded sort method of Collections class that is

Collections.sort(List, Comparator); 

Let's see this example :
package blog.scjp;

public class Student{
 private Integer rollNo;
 private String name;
 private String address;
 
 public Student() {
 }
 
 public Student(Integer rollNo, String name, String address) {
  super();
  this.rollNo = rollNo;
  this.name = name;
  this.address = address;
 }
 public Integer getRollNo() {
  return rollNo;
 }
 public void setRollNo(Integer rollNo) {
  this.rollNo = rollNo;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }

 @Override
 public String toString() {
  return "Student [rollNo=" + rollNo + ", name=" + name + ", address=" + address + "]";
 }

}

In this example Student class does not implements any interface.

Now let's sort using comparator

package blog.scjp;

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

public class MainTestBlog {

  public static void main(String[] args) {
    Student student1 = new Student(1, "Santosh", "Noida");
    Student student2 = new Student(3, "Amit", "GZB");
    Student student3 = new Student(2, "Naman", "Delhi");
    Student student4 = new Student(4, "Raj", "Greater Noida");
    Student student5 = new Student(5, "Rajesh", "Delhi");
    Student student6 = new Student(1, "Naveen", "Patna");

    List<Student> students = new ArrayList<Student>();
    students.add(student1);
    students.add(student2);
    students.add(student3);
    students.add(student4);
    students.add(student5);
    students.add(student6);

    System.out.println("Before Sorting");
    print(students);

    // Annonymous class being used for Comparator
    // how to sort arraylist in java
    Collections.sort(students, new Comparator<Student>() {
      public int compare(Student s1, Student s2) {
        // for Ascending order
        return s1.getName().compareTo(s2.getName());
        // for descending order
        // return s2.getName().compareTo(s1.getName());
      };
    });


    // Java 8 we can use this code to sort using student name.
    // how to sort arraylist in java 8
    /* Comparator<Student> NAME_SORT = (Student s1, Student s2) ->  s1.getName().compareTo(s2.getName());
     Collections.sort(students, NAME_SORT);*/
     
     
    // Java 8 we can use this code to sort using student role no.
    // how to sort arraylist in java 8
    /* Comparator<Student> ROLE_NO_SORT = (Student s1, Student s2) -> s1.getRollNo().compareTo(s2.getRollNo());
     Collections.sort(students, ROLE_NO_SORT);*/
     
    // Java 8 we can use this code to sort using student role no.
    // how to sort arraylist in java 8
    /* Comparator<Student> ADDRESS_SORT = (Student s1, Student s2) -> s1.getAddress().compareTo(s2.getAddress());
     Collections.sort(students, ADDRESS_SORT);*/
    
    
    System.out.println("After Sorting");
    print(students);
  }


  static void print(List<Student> students) {
    for (Student student : students) {
      System.out.println("NAME  >  " + student.getName() +"   AGE > "+ student.getRollNo() + "   ADDRESS > " + student.getAddress());
    }
    System.out.println("");
  }

}

OUTPUT

Before Sorting
NAME  >  Santosh   AGE > 1   ADDRESS > Noida
NAME  >  Amit   AGE > 3   ADDRESS > GZB
NAME  >  Naman   AGE > 2   ADDRESS > Delhi
NAME  >  Raj   AGE > 4   ADDRESS > Greater Noida
NAME  >  Rajesh   AGE > 5   ADDRESS > Delhi
NAME  >  Naveen   AGE > 1   ADDRESS > Patna

After Sorting
NAME  >  Amit   AGE > 3   ADDRESS > GZB
NAME  >  Naman   AGE > 2   ADDRESS > Delhi
NAME  >  Naveen   AGE > 1   ADDRESS > Patna
NAME  >  Raj   AGE > 4   ADDRESS > Greater Noida
NAME  >  Rajesh   AGE > 5   ADDRESS > Delhi
NAME  >  Santosh   AGE > 1   ADDRESS > Noida

In above example  I have given two approach to sort student class object. first way is old one approach. Second is using java 8 lambda expression

Second one is looking pretty clean way to sort the list. using lambda I have written sorting logic on three different property of student class.


If You have some suggestion please comment below.



OCJP certification dumps


No comments:

Post a Comment