Domain of Java programming, ArrayList stands out as a versatile and commonly used data structure. Often, the need arises to sort this dynamic array, whether to enhance data visualization, optimize searches, or streamline data manipulation. This article is geared towards elucidating how to Sort ArrayList in Java
Using Collections.sort() to Sort ArrayList in Java
The Java Collections framework provides a powerful utility method – Collections.sort()
. It serves as an efficient tool to Sort ArrayList in Java.
Example:
When this code is executed, it sorts the ArrayList in natural order.
Sorting with Custom Comparators
What if you need a custom sorting order? Java’s got you covered. You can define custom comparators to Sort ArrayList in Java based on specific criteria.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SortArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(15);
numbers.add(7);
numbers.add(22);
Comparator<Integer> reverseOrder = Collections.reverseOrder();
Collections.sort(numbers, reverseOrder);
System.out.println("ArrayList sorted in descending order: " + numbers);
}
}
This will sort the numbers in descending order
Sort ArrayList of Custom Objects
Handling primitive types and strings is straightforward, but what about custom objects? Java provides a solution for this too. To Sort ArrayList in Java containing custom objects, one can employ a comparator or make the custom class implement the Comparable
interface, offering structured sorting even for complex data.
Example:
import java.util.ArrayList;
import java.util.Collections;
class Student implements Comparable<Student> {
int rollNo;
String name;
Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
@Override
public int compareTo(Student s) {
return this.name.compareTo(s.name);
}
}
public class SortArrayListExample {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(3, "John"));
students.add(new Student(1, "Alice"));
students.add(new Student(2, "Bob"));
Collections.sort(students);
for(Student s: students) {
System.out.println("Student: " + s.name + ", Roll No: " + s.rollNo);
}
}
}
Stream API and Sorting
Introduced in Java 8, the Stream API has revolutionized data manipulation. You can sort ArrayLists using this API, which provides a more functional programming approach.
Example:
import java.util.ArrayList;
import java.util.stream.Collectors;
public class StreamSortExample {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<>();
cities.add("New York");
cities.add("Los Angeles");
cities.add("Chicago");
List<String> sortedCities = cities.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted cities using Stream API: " + sortedCities);
}
}
Explanation:
- Imports:
java.util.ArrayList
: Allows you to use theArrayList
class which is a part of Java’s collections framework.java.util.stream.Collectors
: This is used to get various methods that work with streams to transform them into other data structures.
- Class Definition:
- The class
StreamSortExample
has been defined.
- The class
- Main Method:
- This is the entry point for the Java program.
- ArrayList Initialization:
ArrayList<String> cities = new ArrayList<>();
: An empty ArrayList named ‘cities’ is created which will hold String values.cities.add("New York");
,cities.add("Los Angeles");
, andcities.add("Chicago");
: Three city names are added to the ‘cities’ ArrayList.
- Using the Stream API to Sort:
cities.stream()
: This converts the ArrayList into a Stream. Streams in Java 8+ are sequences of elements (in this case, city names) which can be processed in parallel or sequentially..sorted()
: This method sorts the elements of the stream. Since we’re working with Strings (city names), it will use their natural order (alphabetical)..collect(Collectors.toList())
: This method transforms the sorted stream back into a list. TheCollectors.toList()
method tells the stream to gather its elements into a new List.
- Storing the Result & Output:
List<String> sortedCities
: The sorted city names are stored in a new list called ‘sortedCities’.System.out.println("Sorted cities using Stream API: " + sortedCities);
: This line prints out the sorted cities to the console.
When you run the program, it will output:
Sorted cities using Stream API: [Chicago, Los Angeles, New York]
//This is because, alphabetically, "Chicago" comes before "Los Angeles" and "New York".
Conclusion: Sorting Made Simple
In Java, multiple pathways allow you to Sort ArrayList, catering to various data types and requirements. By leveraging Java’s robust libraries and utilities, you can achieve precise, efficient sorting with relative ease. Whether you’re handling primitive types, strings, or custom objects, the techniques showcased above ensure that you can tackle any sorting challenge head-on.