How To Sort An Arraylist In Java

Sorting in Java refers to the process of arranging elements in a specific order, either in ascending or descending order. The elements in a collection can be sorted using various algorithms, such as bubble sort, insertion sort, merge sort and quicksort.

In Java, you can sort collections of objects using the sort() method from the Collections class or the Arrays class. The sort() method takes the collection to be sorted as an argument and returns the sorted collection.

How to sort array list in Java

There are several approaches to sort an ArrayList in Java:

  1. Using the sort() method from the Collections class: The sort() method sorts the elements in the ArrayList in ascending order, using the natural order of the elements. If the elements do not have a natural order, you can pass a custom Comparator to the sort() method to specify the order.
  2. Using the sort() method from the Arrays class: The sort() method from the Arrays class can be used to sort an ArrayList by first converting it to an array using the toArray() method and then sorting the array using the sort() method.
  3. Using the Collections.sort() method with a custom Comparator: You can pass a custom Comparator to the sort() method from the Collections class to sort the ArrayList based on a specific attribute or field of the elements in the list.

Let’s dive in more with examples to each approach.

Approach 1: Using the sort() method from the Collections class

Here is an example of using the sort() method from the Collections class to sort an ArrayList of strings in ascending order:

import java.util.ArrayList;
import java.util.Collections;
public class Main {
  public static void main(String[] args) {
    ArrayList list = new ArrayList();
    list.add("dog");
    list.add("cat");
    list.add("apple");
    list.add("banana");
    Collections.sort(list);
    System.out.println("Sorted list: " + list);
  }
}

Output:

Sorted list: [apple, banana, cat, dog]

In this example, the ArrayList of strings is sorted in ascending order using the sort() method from the Collections class. The output shows that the elements in the ArrayList have been sorted in alphabetical order.

Approach 2: Using the sort() method from the Arrays class

Here is an example of using the sort() method from the Arrays class to sort an ArrayList of integers:

import java.util.ArrayList;
import java.util.Arrays;
public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(3);
    list.add(1);
    list.add(4);
    list.add(1);
    list.add(5);
    Integer[] array = list.toArray(new Integer[0]);
    Arrays.sort(array);
    System.out.println("Sorted list: " + Arrays.toString(array));
  }
}

Output:

Sorted list: [1, 1, 3, 4, 5]

In this example, the ArrayList of integers is first converted to an array using the toArray() method. Then, the array is sorted using the sort() method from the Arrays class. The sorted array is then displayed using the toString() method from the Arrays class.

Approach 3: Using the Collections.sort() method with a custom Comparator

Here is an example of using the Collections.sort() method with a custom Comparator to sort an ArrayList of Person objects based on their age attribute:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person {
  private int age;
  private String name;
  public Person(int age, String name) {
    this.age = age;
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public String getName() {
    return name;
  }
  @Override
  public String toString() {
    return "Person [age=" + age + ", name=" + name + "]";
  }
}
public class Main {
  public static void main(String[] args) {
    ArrayList<Person> list = new ArrayList<Person>();
    list.add(new Person(30, "John"));
    list.add(new Person(25, "Jane"));
    list.add(new Person(35, "Jim"));
    list.add(new Person(20, "Joe"));
    Collections.sort(list, new Comparator<Person>() {
      @Override
      public int compare(Person p1, Person p2) {
        return p1.getAge() - p2.getAge();
      }
    });
    System.out.println("Sorted list: " + list);
  }
}

Output:

Sorted list: [Person [age=20, name=Joe], Person [age=25, name=Jane], Person [age=30, name=John], Person [age=35, name=Jim]]

In this example, a custom Comparator is passed to the sort() method from the Collections class to sort the ArrayList of Person objects based on their age attribute. The compare() method in the custom Comparator compares the age attribute of two Person objects and returns a positive, negative, or zero value depending on the order of the objects. The sorted ArrayList is then displayed.

Best Approach for Sorting in Java

The sort() method from the Arrays class is the best approach for sorting arrays in Java due to the following reasons:

  1. Performance: The sort() method from the Arrays class uses the efficient dual-pivot quicksort algorithm.
  2. Simplicity: The sort() method from the Arrays class is very simple to use, and sorting an array is as simple.
  3. In-Place Sorting: The sort() method from the Arrays class sorts arrays in place, meaning that it does not create a new sorted array.
  4. Built-in Support for Primitive Data Types: The sort() method from the Arrays class has built-in support for primitive data types.

Sample Problems for Sorting in Java

How to sort a list of objects in java

Write a code to obtain a list of objects with age and name using Collections.sort() method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Person {
  private int age;
  private String name;
  public Person(int age, String name) {
    this.age = age;
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public String getName() {
    return name;
  }
  @Override
  public String toString() {
    return "Person [age=" + age + ", name=" + name + "]";
  }
}
public class Main {
  public static void main(String[] args) {
    List<Person> list = new ArrayList<Person>();
    list.add(new Person(30, "John"));
    list.add(new Person(25, "Jane"));
    list.add(new Person(35, "Jim"));
    list.add(new Person(20, "Joe"));
    Collections.sort(list, (p1, p2) -> p1.getAge() - p2.getAge());
    System.out.println("Sorted list: " + list);
  }
}

Output:

Sorted list: [Person [age=20, name=Joe], Person [age=25, name=Jane], Person [age=30, name=John], Person [age=35, name=Jim]]

In this example, a List of Person objects is created and then sorted using the Collections.sort() method. A Comparator is passed as an argument to the sort() method to sort the list based on the age attribute of the Person objects. The sorted list is then displayed.

How to sort array of integers in java:

Write a code for sorting array of integers by taking 4 integers by using Arrays.sort() method.

import java.util.Arrays;
public class Main {
  public static void main(String[] args) {
    int[] array = {30, 25, 35, 20};
    Arrays.sort(array);
    System.out.println("Sorted array: " + Arrays.toString(array));
  }
}

Output:

Sorted array: [20, 25, 30, 35]

In this example, an array of integers is created and then sorted using the Arrays.sort() method. The sorted array is then displayed using the Arrays.toString() method.

How to sort array elements in java

Here is an example of using the Arrays.sort() method to sort an array of elements in Java:

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    String[] array = {"John", "Jane", "Jim", "Joe"};
    Arrays.sort(array);
    System.out.println("Sorted array: " + Arrays.toString(array));
  }
}

Output:

Sorted array: [Jane, Jim, Joe, John]

In this example, an array of elements (strings) is created and then sorted using the Arrays.sort() method. The sorted array is then displayed using the Arrays.toString() method.

Conclusion

Sorting in Java refers to the process of arranging elements in a specific order, either in ascending or descending order. Java provides several built-in methods and classes for sorting elements, such as the sort() method from the java.util.Arrays class and the sort() method from the java.util.Collections class.

The sorting process can be based on different criteria, such as the natural order of elements, a custom comparison function, or a custom comparator.