Java Algorithms

Java Collections Algorithms

The Java Collections Framework includes a utility class named java.util.Collections (with an 's' at the end) that consists exclusively of static methods that operate on or return collections.

This class provides a set of powerful, reusable algorithms that can save you a lot of time and effort.

Understand the underlying data structures in our Java Collections guide.

Sorting with Collections.sort()

The sort() method sorts the elements of a List into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface.

Learn more about implementing behavior in our Java Interfaces guide.

Sorting a List

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

public class Main { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Charlie"); names.add("Alice"); names.add("Bob"); System.out.println("Original list: " + names); Collections.sort(names); System.out.println("Sorted list: " + names); } }


Shuffling with Collections.shuffle()

The shuffle() method randomly permutes the specified list. This is useful for games, simulations, or any application where you need to randomize the order of elements.

Shuffling a List

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

public class Main { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); for (int i = 1; i <= 5; i++) { numbers.add(i); } System.out.println("Original list: " + numbers); Collections.shuffle(numbers); System.out.println("Shuffled list: " + numbers); } }


Other Useful Algorithms

The Collections class provides many other useful static methods.

Method Description
reverse(List<?> list) Reverses the order of the elements in the specified list.
binarySearch(List<?> list, T key) Searches the specified list for an object using the binary search algorithm. The list must be sorted beforehand.
max(Collection<?> coll) Returns the maximum element of the given collection, according to the natural ordering of its elements.
min(Collection<?> coll) Returns the minimum element of the given collection.
fill(List<?> list, T obj) Replaces all of the elements of the specified list with the specified element.
frequency(Collection<?> c, Object o) Returns the number of times the specified object occurs in the specified collection.

Using Other Algorithms

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

public class Main { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(50); numbers.add(20); System.out.println("Max element: " + Collections.max(numbers)); System.out.println("Min element: " + Collections.min(numbers)); Collections.reverse(numbers); System.out.println("Reversed list: " + numbers); } }


Advanced: Custom Sorting with Comparator.comparing()

While Collections.sort(list) uses the "natural" ordering (like alphabetical for strings), you often need to sort a list of custom objects by a specific property. Modern Java provides extremely clean utility methods via Comparator.comparing().

Sorting with Comparators

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

class Employee { String name; double salary;

public Employee(String name, double salary) { this.name = name; this.salary = salary; } @Override public String toString() { return name + " ($" + salary + ")"; } }

public class Main { public static void main(String[] args) { List<Employee> employees = new ArrayList<>(); employees.add(new Employee("Alice", 60000)); employees.add(new Employee("Bob", 45000)); employees.add(new Employee("Charlie", 75000)); // Sort by salary (ascending) using Java 8 method references Collections.sort(employees, Comparator.comparingDouble(e -> e.salary)); System.out.println("Sorted by salary: " + employees); // Sort by salary descending Collections.sort(employees, Comparator.comparingDouble((Employee e) -> e.salary).reversed()); System.out.println("Sorted descending: " + employees); } }


Advanced: Unmodifiable and Synchronized Wrappers

The Collections class also provides methods to create "wrappers" around your existing collections to change their behavior.

Creating Unmodifiable Collections

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

public class Main { public static void main(String[] args) { List<String> originalList = new ArrayList<>(); originalList.add("Red"); originalList.add("Blue"); // Wrap the list List<String> safeList = Collections.unmodifiableList(originalList); System.out.println(safeList); // safeList.add("Green"); // This will throw an UnsupportedOperationException! } }


Advanced Notes: Algorithm Thinking


Exercise

?

Which method from the Collections class is used to sort a List?