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 alphabetically.

import java.util.LinkedList;
 
public class Main {
  public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<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 in the list. A Comparator can be utilized to compare element pairs. This comparator can be established through a lambda expression compatible with Java’s Comparator interface’s compare() method.

If null is provided to the method, 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 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

Utilize a lambda expression to sort a list in descending alphabetical order.

import java.util.LinkedList;
 
public class Main {
  public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<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);
  }
}