Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

sort()

Example

Arrange a list in alphabetical order.

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 organizes items within the list. A Comparator, defined by a lambda expression compatible with Java’s Comparator interface’s compare() method, can be utilized to compare pairs of elements.

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

Syntax

public void sort(Comparator compare)

 

Parameter Values

Parameter

Description

compare

Mandatory: A comparator or lambda expression that compares pairs of items in the list. Use null to compare items naturally based on their data type.

Technical Details

Java version:

1.8+

More Examples

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( (a, b) -> { return -1 * a.compareTo(b); } );
    System.out.println(cars);
  }
}