bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java ArrayList sort() Method

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java ArrayList sort() Method?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ java.util.ArrayList;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The sort() method sorts items in the list.
Definition and Usage
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