Common Utility Methods
Sorting Methods
sort()
Sorts collections in natural ascending order or using a custom comparator.
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
Collections.sort(numbers); // Sorts in ascending order
reverseOrder()
Creates a comparator that imposes the reverse of the natural ordering.
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
Collections.sort(numbers, Collections.reverseOrder());
Search and Manipulation Methods
binarySearch()
Performs binary search on a sorted list.
List<Integer> sortedList = Arrays.asList(1, 2, 3, 4, 5);
int index = Collections.binarySearch(sortedList, 3); // Returns 2
frequency()
Counts the number of elements in a collection.
List<String> fruits = Arrays.asList("apple", "banana", "apple", "cherry");
int appleCount = Collections.frequency(fruits, "apple"); // Returns 2
reverse()
Reverses the order of elements in a list.
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
Collections.reverse(names);
shuffle()
Randomly reorders list elements.
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.shuffle(numbers);
Synchronization Methods
synchronizedList()
Creates a thread-safe synchronized list.
List<String> threadSafeList = Collections.synchronizedList(new ArrayList<>());
Utility Operations
min()
and max()
Find minimum and maximum elements in a collection.
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
int minimum = Collections.min(numbers); // Returns 1
int maximum = Collections.max(numbers); // Returns 9
Method Comparison
Method |
Purpose |
Time Complexity |
sort() |
Sorting collection |
O(n log n) |
binarySearch() |
Searching sorted list |
O(log n) |
shuffle() |
Randomizing list |
O(n) |
frequency() |
Counting occurrences |
O(n) |
Practical Considerations
graph TD
A[Collections Utility Methods]
A --> B[Sorting]
A --> C[Searching]
A --> D[Transformation]
A --> E[Synchronization]
Best Practices
- Always ensure lists are sorted before using
binarySearch()
- Use appropriate synchronization for multi-threaded environments
- Consider performance for large collections
Learning with LabEx
At LabEx, we encourage exploring these methods through practical coding exercises to gain deeper understanding of their applications and nuances.