Skip to lesson

Search and sort a list

A list can answer two everyday questions for you: "is this item here, and where?" and "put these items in order". contains and indexOf search, Collections.sort sorts, and Collections.binarySearch searches a sorted list very fast.

Search with contains and indexOf

A linear search checks the items one by one, from one end, until it finds a match or reaches the end. A list of n items may need n checks, so it is O(n): the time grows with the size of the list.

contains(item) returns true or false. indexOf(item) returns the index of the first equal item, and lastIndexOf(item) the index of the last one. Both return -1 when the item is not in the list.

Example 1 · contains, indexOf and lastIndexOf

LibraryLogDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class LibraryLogDemo {    public static void main(String[] args) {        List<String> issuedTo = new ArrayList<>(List.of("Riya", "Aman", "Riya", "Zoya"));
        System.out.println("Aman borrowed? " + issuedTo.contains("Aman"));        System.out.println("First Riya at " + issuedTo.indexOf("Riya"));        System.out.println("Last Riya at " + issuedTo.lastIndexOf("Riya"));        System.out.println("Kunal at " + issuedTo.indexOf("Kunal"));        System.out.println("riya borrowed? " + issuedTo.contains("riya"));
        String typed = new String("Zoya");        System.out.println("Same object? " + (typed == issuedTo.get(3)));        System.out.println("Zoya found at " + issuedTo.indexOf(typed));    }}
Output
Aman borrowed? true
First Riya at 0
Last Riya at 2
Kunal at -1
riya borrowed? false
Same object? false
Zoya found at 3

What this code does

  • indexOf finds the first Riya (0) and lastIndexOf the last one (2). A missing name gives -1.
  • Lower-case riya is a different String, so contains returns false.
  • typed is a different object (== is false), but indexOf uses equals, so it still finds Zoya.

These methods start at one end and check every item until they find a match. A list of 10 items needs at most 10 checks; a list of 10 lakh items may need 10 lakh.

Summary of the three calls:

  • contains(x) → true / false
  • indexOf(x) → first index of x, or -1
  • lastIndexOf(x) → last index of x, or -1

Search uses equals, not ==

To compare, these methods call equals() on the items, never ==. String overrides equals to compare the text, so a name read from the keyboard or built with new String("Riya") is found.

SearchWithEquals.javaJava
import java.util.*;
public class SearchWithEquals {    public static void main(String[] args) {        List<String> names = List.of("Asha", "Riya", "Ravi");        String typed = new String("Riya");        System.out.println(names.contains(typed));        System.out.println(names.indexOf("riya"));        System.out.println(names.indexOf("Riya "));        System.out.println(names.indexOf(" Riya ".trim()));    }}
Output
true
-1
-1
1

The comparison is exact: "riya" does not match "Riya", and "Riya " with a space does not match either. Clean the text first with trim() and a fixed case if users type it.

For your own classes, equals comes from Object and compares references unless you override it. The lesson Lists of your own objects shows why that matters.

Sort in natural order

Natural order is the default order of a type: numbers from small to large, and Strings in dictionary order by character code. Collections.sort(list) and list.sort(null) sort a list in its natural order.

Collections.sort(list) sorts a list in its natural order. list.sort(null) does the same; null means "no custom order". Both change the list itself and return nothing.

Example 2 · Sorting numbers and names

NaturalOrderDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class NaturalOrderDemo {    public static void main(String[] args) {        List<Integer> marks = new ArrayList<>(List.of(67, 92, 45, 88, 45));        Collections.sort(marks);        System.out.println("Marks: " + marks);
        List<String> names = new ArrayList<>(List.of("meera", "Zoya", "Arjun", "aarav", "Bhavya"));        Collections.sort(names);        System.out.println("Names: " + names);
        List<String> codes = new ArrayList<>(List.of("10", "9", "100", "25"));        codes.sort(null);        System.out.println("Codes as text: " + codes);
        Collections.reverse(marks);        System.out.println("Marks, high to low: " + marks);    }}
Output
Marks: [45, 45, 67, 88, 92]
Names: [Arjun, Bhavya, Zoya, aarav, meera]
Codes as text: [10, 100, 25, 9]
Marks, high to low: [92, 88, 67, 45, 45]

What this code does

  • Numbers sort from small to large, and the duplicate 45s stay side by side.
  • Capital letters come before small letters, so Zoya is before aarav. Strings of digits compare character by character, so "100" is before "25" and "9".
  • Collections.reverse after a sort gives large-to-small order.

Example 3 · Keep the original: sort a copy

TopThreeDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class TopThreeDemo {    public static void main(String[] args) {        List<Integer> byRollNo = new ArrayList<>(List.of(71, 94, 58, 88, 99, 63));
        List<Integer> ranked = new ArrayList<>(byRollNo);        Collections.sort(ranked);        Collections.reverse(ranked);
        System.out.println("Top 3:");        for (int i = 0; i < 3 && i < ranked.size(); i++) {            System.out.println((i + 1) + ". " + ranked.get(i));        }        System.out.println("Roll order kept: " + byRollNo);    }}
Output
Top 3:
1. 99
2. 94
3. 88
Roll order kept: [71, 94, 58, 88, 99, 63]

What this code does

  • new ArrayList<>(byRollNo) makes a second list with the same items. Sorting it does not touch the original.
  • The loop stops at 3 or at the end of the list, so a class with only two students would not crash.

Dictionary order by character code has surprises: all capital letters come before all small letters, so "Zoya" comes before "aarav". Digits are compared one character at a time, so the String "10" comes before "9".

For large-to-small order, sort and then call Collections.reverse(list). To keep the original order too, sort a copy: new ArrayList<>(list).

Predict the output

What order comes out?

Read each snippet and pick what it prints.

Round 1 of 4

Order totals, sorted.

List<Integer> totals = new ArrayList<>(List.of(450, 90, 1200));
Collections.sort(totals);
System.out.println(totals);
Any other order, such as by length, ignoring case, or students by marks, needs a Comparator. The Sorting & Comparing module teaches it.

Binary search on a sorted list

Binary search finds an item in a sorted list by looking at the middle item first and throwing away the half that cannot hold the key. Each step halves the list, so 10 lakh items need only about 20 steps.

Binary search looks at the middle item first. If the key is smaller, it throws away the right half; if larger, the left half. Each step halves what is left, so 10 lakh sorted items need only about 20 steps.

Example 4 · Bug: binarySearch on an unsorted list

UnsortedSearchBugDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class UnsortedSearchBugDemo {    public static void main(String[] args) {        List<Integer> pins = new ArrayList<>(List.of(40, 10, 30, 20, 50));
        System.out.println("indexOf(10): " + pins.indexOf(10));        System.out.println("binarySearch(10): " + Collections.binarySearch(pins, 10));
        Collections.sort(pins);        System.out.println("Sorted: " + pins);        System.out.println("binarySearch(10): " + Collections.binarySearch(pins, 10));    }}
Output
indexOf(10): 1
binarySearch(10): -1
Sorted: [10, 20, 30, 40, 50]
binarySearch(10): 0

What this code does

  • On the unsorted list, binary search checks the middle (30), decides 10 must be on the left, then sees 40 and gives up: -1, "not found", although 10 is at index 1.
  • There is no exception. Only sorting first makes the answer right: 10 is at index 0 of the sorted list.

Example 5 · Roll number lookup with binarySearch

RollLookupDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class RollLookupDemo {    public static void main(String[] args) {        List<Integer> registered = new ArrayList<>(List.of(1032, 1007, 1045, 1021, 1050));        Collections.sort(registered);        System.out.println("Registered: " + registered);
        int[] queries = { 1045, 1030, 1060 };        for (int roll : queries) {            int result = Collections.binarySearch(registered, roll);            if (result >= 0) {                System.out.println(roll + ": found at index " + result);            } else {                int insertAt = -(result + 1);                System.out.println(roll + ": not registered (result " + result + ", would go at index " + insertAt + ")");            }        }
        int late = 1030;        int pos = -(Collections.binarySearch(registered, late) + 1);        registered.add(pos, late);        System.out.println("After late registration: " + registered);    }}
Output
Registered: [1007, 1021, 1032, 1045, 1050]
1045: found at index 3
1030: not registered (result -3, would go at index 2)
1060: not registered (result -6, would go at index 5)
After late registration: [1007, 1021, 1030, 1032, 1045, 1050]

What this code does

  • 1030 is missing; it belongs at index 2, so the result is -(2) - 1 = -3. -(result + 1) turns -3 back into 2.
  • A key larger than all items gets insertion point size(), here 5, so the result is -6.
  • Adding at the insertion point keeps the list sorted, so later binary searches still work.

Collections.binarySearch(list, key) works only on a list sorted in natural order. On an unsorted list it can return a wrong answer without any error.

It returns the index when the key is found. When the key is missing, it returns a negative number: -(insertion point) - 1. The insertion point is the index where the key would go to keep the list sorted. So -(result + 1) gives that index back.

Sorting costs more than one linear search. Sort once and use binarySearch when you will search the same list many times.

Next step

Check your understanding

12 quick questions