SwadhyAI Notes

All Java notes

Java Collections Methods Reference

›Short versionOpen if you only have a minute.
  • Collections is a utility class of static methods. It is not the same thing as a Collection.
  • sort, reverse, shuffle, fill, and rotate rewrite the list you pass.
  • binarySearch needs a list already sorted with the same ordering. Otherwise the index is undefined.
  • unmodifiableList returns a view. A change through the original list still appears in the view.
  • synchronizedList locks each method call. Iteration still needs the caller to lock the wrapper.
  • copy requires the destination to already be at least as long as the source. max and min throw on an empty collection.

Collections is a utility class with static methods for Lists, Sets, and other Collection objects. Many methods mutate the supplied collection; others return wrappers or generated collections.

Methods

APIParametersReturnsBehaviorWatch for
sort(List<T> list)Mutable list, optional Comparator overload.void.Sorts the list in place.Elements must be mutually comparable unless a comparator is supplied.
binarySearch(List<T> list, T key)Sorted list and search key.Index or negative insertion point encoding.Searches in logarithmic time.Wrong result if list is not sorted the same way.
reverse(List<?> list)Mutable list.void.Reverses element order in place.Throws UnsupportedOperationException for unmodifiable lists.
frequency(Collection<?> c, Object o)Collection and target object.int count.Counts elements equal to target.Uses equals(), so custom equality matters.
unmodifiableList(List<? extends T> list)Backing list.Read-only view.Prevents mutation through the returned reference.Changes to the original list still appear in the view.
synchronizedList(List<T> list)Backing list.Thread-safe wrapper.Synchronizes individual method calls.Iteration still needs manual synchronization on the wrapper.

Which call fits

OptionBest forTradeoff
Collections.sort(list)Sorting existing mutable lists.Mutates the list.
list.stream().sorted()Creating a sorted result without changing source order.More stream machinery and collection step.
List.of(...)Small unmodifiable lists created directly.Rejects nulls and cannot be resized.

Examples

Sort then binary search

java
ArrayList<Integer> values = new ArrayList<>(List.of(8, 3, 5));
Collections.sort(values);

int index = Collections.binarySearch(values, 5);
System.out.println(index); // 1

Read-only view caveat

java
ArrayList<String> base = new ArrayList<>(List.of("A"));
List<String> view = Collections.unmodifiableList(base);

base.add("B");
System.out.println(view); // [A, B]

base is an ArrayList containing A. view is Collections.unmodifiableList(base). Then base.add("B"). What does view contain?

[A, B]. The view did not take a snapshot. view.add("C") throws UnsupportedOperationException, and base is unchanged by that failed call. Collections.sort(view) throws as well, because sort writes through the list it is given.