Dr. Vatsal Shah
Subject Material

Java · Collections · Topic 8

Utility Classes

Process collections and arrays with Collections, Comparable, Comparator, and Arrays utility operations.

Topic progress · 1 of 26 sections

Step 1 of 26

8.1 Collections Utility Class

Learning objective

Distinguish Collection from Collections and call static utility methods.

Java provides Collections for collection algorithms and Arrays for array algorithms.

Static method call
import java.util.Collections;
Collections.sort(list);
Check your understanding: Do we create a Collections object to call sort()?

No. Call Collections.sort(list) directly.

Step 2 of 26

8.2 Sorting a List

Learning objective

Sort numbers and strings by natural order.

CollectionsSortDemo.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsSortDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(40, 10, 30, 20));
        Collections.sort(numbers);
        System.out.println(numbers);

        List<String> names = new ArrayList<>(Arrays.asList("Raj", "Amit", "Neha"));
        Collections.sort(names);
        System.out.println(names);
    }
}
Output
[10, 20, 30, 40]
[Amit, Neha, Raj]
Check your understanding: What is the sorted form of 40, 10, 30, 20?

[10, 20, 30, 40].

Step 3 of 26

8.3 Sorting in Descending Order

Learning objective

Apply a reverse-order comparator.

Descending sort
Collections.sort(numbers, Collections.reverseOrder());
// Modern List form:
numbers.sort(Comparator.reverseOrder());

For 10, 20, 30, 40, the result is [40, 30, 20, 10].

Check your understanding: What is the descending order of 10, 20, 30, 40?

[40, 30, 20, 10].

Step 4 of 26

8.4 Reversing a List

Learning objective

Distinguish reversing the current sequence from sorting descending.

CollectionsReverseDemo.java
import java.util.*;
public class CollectionsReverseDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(10,20,30,40));
        Collections.reverse(numbers);
        System.out.println(numbers);
    }
}
Output
[40, 30, 20, 10]
Check your understanding: What does reverse() do to [10,20,30,40]?

It produces [40,30,20,10].

Step 5 of 26

8.5 Shuffling Elements

Learning objective

Randomize list order and identify appropriate uses.

Shuffle a list
Collections.shuffle(numbers);
System.out.println(numbers);

A possible output is [30, 10, 40, 20], but another run may differ.

Applications

  • Playing cards
  • Quiz-question order
  • Random student selection
Check your understanding: Is shuffle() output deterministic?

No.

Step 6 of 26

8.6 Minimum and Maximum

Learning objective

Find the smallest and largest elements according to their ordering.

CollectionsMinMaxDemo.java
import java.util.*;
public class CollectionsMinMaxDemo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(40,10,30,20);
        System.out.println("Minimum: " + Collections.min(numbers));
        System.out.println("Maximum: " + Collections.max(numbers));
    }
}
Output
Minimum: 10
Maximum: 40
Check your understanding: For [40,10,30,20], what are min and max?

10 and 40.

Step 7 of 26

8.7 Searching with binarySearch()

Learning objective

Sort before binary search and interpret found and missing results.

CollectionsBinarySearchDemo.java
import java.util.*;
public class CollectionsBinarySearchDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(40,10,30,20));
        Collections.sort(numbers);
        int position = Collections.binarySearch(numbers, 30);
        System.out.println("Position: " + position);
        System.out.println(position >= 0 ? "Element found" : "Element not found");
    }
}
Output
Position: 2
Element found
Check your understanding: What must happen before binarySearch()?

The list must be sorted in the same ordering.

Step 8 of 26

8.8 Frequency of an Element

Learning objective

Count equal occurrences without modifying the list.

Count occurrences
List<String> names = Arrays.asList("Amit", "Neha", "Amit", "Raj", "Amit");
int count = Collections.frequency(names, "Amit");
System.out.println(count); // 3
Check your understanding: How often does Amit occur in Amit, Neha, Amit, Raj, Amit?

Three times.

Step 9 of 26

8.9 Replacing All Occurrences

Learning objective

Replace every matching list value.

Replace every Amit
Collections.replaceAll(names, "Amit", "Amit Shah");

Every Amit entry becomes Amit Shah.

Check your understanding: Does replaceAll change only the first match?

No, it replaces all matching occurrences.

Step 10 of 26

8.10 Swapping Elements

Learning objective

Exchange values at two valid indexes.

Swap positions
Collections.swap(numbers, 0, 3);
Effect
BeforeAfter
[10, 20, 30, 40][40, 20, 30, 10]
Check your understanding: What results from swapping indexes 0 and 3 in [10,20,30,40]?

[40,20,30,10].

Step 11 of 26

8.11 Filling a List

Learning objective

Replace every existing element with one value.

CollectionsFillDemo.java
import java.util.*;
public class CollectionsFillDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(10,20,30,40));
        Collections.fill(numbers, 0);
        System.out.println(numbers);
    }
}
Output
[0, 0, 0, 0]
Check your understanding: Does fill() add elements to an empty list?

No.

Step 12 of 26

8.12 Copying a List

Learning objective

Use Collections.copy safely and contrast it with copy construction.

CollectionsCopyDemo.java
import java.util.*;
public class CollectionsCopyDemo {
    public static void main(String[] args) {
        List<Integer> source = Arrays.asList(10,20,30);
        List<Integer> destination = new ArrayList<>(Arrays.asList(0,0,0));
        Collections.copy(destination, source);
        System.out.println(destination);
    }
}
Output
[10, 20, 30]
Independent copy
List<Integer> destination = new ArrayList<>(source);
Check your understanding: Can Collections.copy copy into an empty destination?

No, the destination lacks required positions.

Step 13 of 26

8.13 Rotating Elements

Learning objective

Shift elements cyclically by a signed distance.

CollectionsRotateDemo.java
import java.util.*;
public class CollectionsRotateDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(10,20,30,40,50));
        Collections.rotate(numbers, 2);
        System.out.println(numbers);
    }
}
Output
[40, 50, 10, 20, 30]
Check your understanding: What is rotate([10,20,30,40,50],2)?

[40,50,10,20,30].

Step 14 of 26

8.14 Important Collections Methods

Learning objective

Review the main static collection algorithms.

Collections methods
MethodPurpose
sort()Sorts list elements
binarySearch()Searches a sorted list
reverse()Reverses current order
reverseOrder()Creates descending comparator
shuffle()Randomizes order
min()/max()Find extremes
frequency()Counts occurrences
replaceAll()Replaces matches
swap()Exchanges two positions
fill()Replaces all positions
copy()Copies into an existing destination
rotate()Cyclically shifts elements
Check your understanding: Which method randomizes element order?

shuffle().

Step 15 of 26

8.15 Comparable Interface

Learning objective

Define a class’s natural ordering with compareTo().

Comparable structure
class Student implements Comparable<Student> {
    public int compareTo(Student other) {
        return Integer.compare(this.enrollmentNumber, other.enrollmentNumber);
    }
}
Check your understanding: Which method must Comparable<T> implement?

compareTo(T other).

Step 16 of 26

8.16 Working of compareTo()

Learning objective

Interpret negative, zero, and positive comparison results.

compareTo result
Return valueMeaning
NegativeCurrent object comes before other
ZeroObjects are equal for ordering
PositiveCurrent object comes after other
Check your understanding: Must compareTo() return exactly -1, 0, or 1?

No. Any negative, zero, or positive result has the required meaning.

Step 17 of 26

8.17 Sorting Students Using Comparable

Learning objective

Implement safe natural ordering for Student objects.

StudentComparableDemo.java
import java.util.*;
class Student implements Comparable<Student> {
    int enrollmentNumber; String name;
    Student(int number, String name) { this.enrollmentNumber=number; this.name=name; }
    public int compareTo(Student other) {
        return Integer.compare(this.enrollmentNumber, other.enrollmentNumber);
    }
    public String toString() { return enrollmentNumber + " - " + name; }
}
public class StudentComparableDemo {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student(103,"Raj"));
        students.add(new Student(101,"Amit"));
        students.add(new Student(102,"Neha"));
        Collections.sort(students);
        students.forEach(System.out::println);
    }
}
Output
101 - Amit
102 - Neha
103 - Raj
Check your understanding: Which student appears first after sorting 103, 101, and 102?

Enrollment 101, Amit.

Step 18 of 26

8.18 Comparator Interface

Learning objective

Define an external custom ordering with compare().

Name comparator
class NameComparator implements Comparator<Student> {
    public int compare(Student s1, Student s2) {
        return s1.name.compareTo(s2.name);
    }
}
Collections.sort(students, new NameComparator());
Check your understanding: Which Comparator method compares two objects?

compare(object1, object2).

Step 19 of 26

8.19 Multiple Comparators

Learning objective

Provide several independent orderings for one class.

StudentComparatorDemo.java
import java.util.*;
class Learner {
    String name; int marks;
    Learner(String name,int marks){this.name=name;this.marks=marks;}
    public String toString(){return name+" - "+marks;}
}
public class StudentComparatorDemo {
    public static void main(String[] args) {
        List<Learner> students = new ArrayList<>(Arrays.asList(
            new Learner("Neha",88), new Learner("Amit",92), new Learner("Raj",75)));
        students.sort(Comparator.comparing(s -> s.name));
        System.out.println(students);
        students.sort(Comparator.comparingInt(s -> s.marks));
        System.out.println(students);
    }
}
Output
[Amit - 92, Neha - 88, Raj - 75]
[Raj - 75, Neha - 88, Amit - 92]

Possible criteria

  • Enrollment number
  • Name
  • Marks
  • Age
  • Salary
  • Joining date
Check your understanding: Can one class have both name and marks comparators?

Yes.

Step 20 of 26

8.20 Comparable versus Comparator

Learning objective

Choose between natural and custom ordering strategies.

Ordering interfaces
ComparableComparator
Natural orderingCustom ordering
java.langjava.util
Implemented by sorted classUsually separate
compareTo()compare()
Normally one primary orderMultiple orders
Collections.sort(list)Collections.sort(list, comparator)
Check your understanding: Which interface avoids modifying the original class?

Comparator.

Step 21 of 26

8.21 Arrays Utility Class

Learning objective

Identify static array-processing operations.

Arrays methods
MethodPurpose
sort()Sorts an array
binarySearch()Searches a sorted array
equals()Compares array contents
fill()Fills with a value
copyOf()Copies an array
copyOfRange()Copies a range
toString()Readable contents
asList()Fixed-size object-array list view
Check your understanding: Which method renders readable array contents?

Arrays.toString().

Step 22 of 26

8.22 Sorting and Searching an Array

Learning objective

Sort an array before applying binary search.

ArraysUtilityDemo.java
import java.util.Arrays;
public class ArraysUtilityDemo {
    public static void main(String[] args) {
        int[] numbers = {40,10,30,20};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));
        System.out.println("Position: " + Arrays.binarySearch(numbers,30));
    }
}
Output
[10, 20, 30, 40]
Position: 2
Check your understanding: What index contains 30 after sorting [40,10,30,20]?

Index 2.

Step 23 of 26

8.23 Filling and Copying Arrays

Learning objective

Fill all positions and copy to a differently sized array.

ArraysFillCopyDemo.java
import java.util.Arrays;
public class ArraysFillCopyDemo {
    public static void main(String[] args) {
        int[] filled = new int[5];
        Arrays.fill(filled,10);
        System.out.println(Arrays.toString(filled));
        int[] copy = Arrays.copyOf(new int[]{10,20,30},5);
        System.out.println(Arrays.toString(copy));
    }
}
Output
[10, 10, 10, 10, 10]
[10, 20, 30, 0, 0]
Check your understanding: What fills the two extra int positions in copyOf(original,5)?

Zero.

Step 24 of 26

8.24 Comparing Arrays

Learning objective

Compare contents rather than reference identity.

ArraysCompareDemo.java
import java.util.Arrays;
public class ArraysCompareDemo {
    public static void main(String[] args) {
        int[] first={10,20,30}; int[] second={10,20,30};
        System.out.println(Arrays.equals(first,second));
        System.out.println(first == second);
    }
}
Output
true
false
Check your understanding: What does Arrays.equals return for two separate {10,20,30} arrays?

true.

Step 25 of 26

8.25 Converting an Array into a List

Learning objective

Understand the fixed-size list view returned by Arrays.asList.

Fixed-size view
String[] names = {"Amit","Neha","Raj"};
List<String> list = Arrays.asList(names);
list.set(0,"Riya");
// list.add("Priya"); // UnsupportedOperationException
Resizable copy
List<String> list = new ArrayList<>(Arrays.asList(names));
Check your understanding: Which exception can add() cause on the fixed-size view?

UnsupportedOperationException.

Step 26 of 26

8.26 Collections versus Arrays

Learning objective

Select the utility class that matches the data structure.

Utility-class comparison
CollectionsArrays
Operates mainly on collectionsOperates on arrays
Collections.sort()Arrays.sort()
Collections.binarySearch()Arrays.binarySearch()
Provides shuffle and rotateProvides array copying
Located in java.utilLocated in java.util
Check your understanding: Which class provides shuffle() and rotate()?

Collections.