bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java ArrayList sort() Method

❮ ArrayList Methods

Example

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    cars.sort(null);
    System.out.println(cars);
  }
}

Definition and Usage

The sort() method sorts items in the list. A Comparator can be used to compare pairs of elements. The comparator can be defined by a lambda expression which is compatible with the compare() method of Java's Comparator interface.

If null is passed into the method then items will be sorted naturally based on their data type (e.g. alphabetically for strings, numerically for numbers). Non-primitive types must implement Java's Comparable interface in order to be sorted without a comparator.

Syntax

public void sort(Comparator
compare )

Parameter Values

ParameterDescription
compareRequired. A comparator or lambda expression which compares pairs of items in the list. Pass null to compare items naturally by their data type.

Technical Details

Java version:1.8+

Previous

Java ArrayList size() Method

Next

Java ArrayList spliterator() Method