Java · Collections · Topic 8
Utility Classes
Process collections and arrays with Collections, Comparable, Comparator, and Arrays utility operations.
Step 1 of 26
8.1 Collections Utility Class
Distinguish Collection from Collections and call static utility methods.
Java provides Collections for collection algorithms and Arrays for array algorithms.
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
Sort numbers and strings by natural order.
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);
}
}[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
Apply a reverse-order comparator.
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
Distinguish reversing the current sequence from sorting descending.
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);
}
}[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
Randomize list order and identify appropriate uses.
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
Find the smallest and largest elements according to their ordering.
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));
}
}Minimum: 10
Maximum: 40Check your understanding: For [40,10,30,20], what are min and max?
10 and 40.
Step 7 of 26
8.7 Searching with binarySearch()
Sort before binary search and interpret found and missing results.
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");
}
}Position: 2
Element foundCheck 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
Count equal occurrences without modifying the list.
List<String> names = Arrays.asList("Amit", "Neha", "Amit", "Raj", "Amit");
int count = Collections.frequency(names, "Amit");
System.out.println(count); // 3Check your understanding: How often does Amit occur in Amit, Neha, Amit, Raj, Amit?
Three times.
Step 9 of 26
8.9 Replacing All Occurrences
Replace every matching list value.
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
Exchange values at two valid indexes.
Collections.swap(numbers, 0, 3);| Before | After |
|---|---|
| [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
Replace every existing element with one value.
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);
}
}[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
Use Collections.copy safely and contrast it with copy construction.
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);
}
}[10, 20, 30]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
Shift elements cyclically by a signed distance.
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);
}
}[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
Review the main static collection algorithms.
| Method | Purpose |
|---|---|
| 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
Define a class’s natural ordering with compareTo().
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()
Interpret negative, zero, and positive comparison results.
| Return value | Meaning |
|---|---|
| Negative | Current object comes before other |
| Zero | Objects are equal for ordering |
| Positive | Current 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
Implement safe natural ordering for Student objects.
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);
}
}101 - Amit
102 - Neha
103 - RajCheck your understanding: Which student appears first after sorting 103, 101, and 102?
Enrollment 101, Amit.
Step 18 of 26
8.18 Comparator Interface
Define an external custom ordering with compare().
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
Provide several independent orderings for one class.
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);
}
}[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
Choose between natural and custom ordering strategies.
| Comparable | Comparator |
|---|---|
| Natural ordering | Custom ordering |
| java.lang | java.util |
| Implemented by sorted class | Usually separate |
| compareTo() | compare() |
| Normally one primary order | Multiple 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
Identify static array-processing operations.
| Method | Purpose |
|---|---|
| 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
Sort an array before applying binary search.
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));
}
}[10, 20, 30, 40]
Position: 2Check your understanding: What index contains 30 after sorting [40,10,30,20]?
Index 2.
Step 23 of 26
8.23 Filling and Copying Arrays
Fill all positions and copy to a differently sized array.
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));
}
}[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
Compare contents rather than reference identity.
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);
}
}true
falseCheck 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
Understand the fixed-size list view returned by Arrays.asList.
String[] names = {"Amit","Neha","Raj"};
List<String> list = Arrays.asList(names);
list.set(0,"Riya");
// list.add("Priya"); // UnsupportedOperationExceptionList<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
Select the utility class that matches the data structure.
| Collections | Arrays |
|---|---|
| Operates mainly on collections | Operates on arrays |
| Collections.sort() | Arrays.sort() |
| Collections.binarySearch() | Arrays.binarySearch() |
| Provides shuffle and rotate | Provides array copying |
| Located in java.util | Located in java.util |
Check your understanding: Which class provides shuffle() and rotate()?
Collections.