Utilities

There are a number of other useful utilities in the Collections class:

max(Collection)

min(Collection)

Produces the maximum or minimum element in the argument using the natural comparison method of the objects in the Collection.

max(Collection, Comparator)

min(Collection, Comparator)

Produces the maximum or minimum element in the Collection using the Comparator.

indexOfSubList(List source, List target)

Produces starting index of the first place where target appears inside source.

lastIndexOfSubList(List source, List target)

Produces starting index of the last place where target appears inside source.

replaceAll(List list, Object oldVal, Object newVal)

Replace all oldVal with newVal.

reverse( )

Reverses all the elements in place.

rotate(List list, int distance)

Moves all elements forward by distance, taking the ones off the end and placing them at the beginning.

copy(List dest, List src)

Copies elements from src to dest.

swap(List list, int i, int j)

Swaps elements at locations i and j in list. Probably faster than what youd write by hand.

fill(List list, Object o)

Replaces all the elements of list with o.

nCopies(int n, Object o)

Returns an immutable List of size n whose references all point to o.

enumeration(Collection)

Produces an old-style Enumeration for the argument.

list(Enumeration e)

Returns an ArrayList generated using the Enumeration. For converting from legacy code.

Note that min( ) and max( ) work with Collection objects, not with Lists, so you dont need to worry about whether the Collection should be sorted or not. (As mentioned earlier, you do need to sort( ) a List or an array before performing a binarySearch( ).)