Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Collection Algorithms

Java Collection Algorithms

Java collection algorithms refer to a set of static methods provided in the java.util.Collections class, used to perform common operations such as sorting, searching, shuffling, and filling on collections (List, Set, Map, etc.).

These algorithms are built into the JDK and highly optimized; developers do not need to write them from scratch and can call them directly.


Overview of Collections Algorithms

java.util.Collections is a utility class where all methods are static, similar to the Arrays utility class for operating on arrays.

The following table lists the most commonly used collection algorithms and their purposes:

Algorithm Category Method Names Description
Sorting sort() Sort a List in ascending order
Shuffle shuffle() Randomly shuffle the order of elements in a List
Reverse reverse() Reverse the order of elements in a List
Binary Search binarySearch() Binary search for a specified element in an ordered List
Fill fill() Replace all elements in a List with a specified element
Copy copy() Copy elements from one List to another
Max/Min Value max() / min() Return the maximum or minimum element in the collection
Frequency Count frequency() Return the number of times a specified element appears in the collection
Disjoint Check disjoint() Determine whether two collections have common elements
Immutable Collection unmodifiableXxx() Return a read-only view of the collection
Thread Safety synchronizedXxx() Return a thread-safe collection wrapper

Sorting

Collections.sort() is the most commonly used collection algorithm, arranging the elements in a List in ascending order.

Under the hood it uses an optimized merge sort (TimSort), with a time complexity of O(n log n) and stable performance.

The sorting process is shown in the figure below:

Original list 5 2 8 1 9 sort() Sorted list 1 2 5 8 9 Custom Sorting Natural order Comparable interface Custom comparator Comparator interface Reverse order sorting Comparator.reverseOrder()

Natural order sorting

After the element class implements the Comparable interface, you can directly call sort() to arrange in natural order.

Example

import

java.util.ArrayList

;

import

java.util.Collections

;

import

java.util.List

;

public

class

SortExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        List

<
String
names
=
new
ArrayList
<>
(
)

;

        names.

add

(

"runoob"

)

;

        names.

add

(

"RUNOOB"

)

;

        names.

add

(

"apple"

)

;

        names.

add

(

"banana"

)

;

       

System

.

out

.

println

(

"Before sorting: "

names

)

;

       

// Natural order sorting (by Unicode code point)

       

Collections

.

sort

(

names

)

;

       

System

.

out

.

println

(

"After sorting: "

names

)

;

   

}

}

Output result:


排序前: [runoob, RUNOOB, apple, banana]
排序后: [RUNOOB, apple, banana, runoob]

Custom Comparator sorting

Using a Comparator allows sorting by any custom rule without modifying the element class itself.

Example: Sort by string length

import

java.util.ArrayList

;

import

java.util.Collections

;

import

java.util.Comparator

;

import

java.util.List

;

public

class

CustomSortExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        List

<
String
words
=
new
ArrayList
<>
(
)

;

        words.

add

(

"runoob"

)

;

        words.

add

(

"java"

)

;

        words.

add

(

"algorithm"

)

;

        words.

add

(

"C"

)

;

       

System

.

out

.

println

(

"Before sorting: "

words

)

;

       

// Sort in ascending order by string length

       

Collections

.

sort

(

words,

new

Comparator

<
String
(
)
{
@Override
public
int
compare
(
String
s1,
String
s2
)
{
return

s1.

length

(

)

s2.

length

(

)

;

           

}

       

}

)

;

       

System

.

out

.

println

(

"After sorting by length: "

words

)

;

   

}

}

Output result:


排序前: [runoob, java, algorithm, C]
按长度排序后: [C, java, runoob, algorithm]

Java 8+ can use Lambda expressions to simplify the writing:

Example: Lambda style

// Lambda expression sorting by length

Collections

.

sort

(

words,

(

s1, s2

)

->

s1.

length

(

)

s2.

length

(

)

)

;

// Or use Comparator.comparingInt

Collections

.

sort

(

words,

Comparator

.

comparingInt

(

String

::

length

)

)

;

// Reverse order sorting

Collections

.

sort

(

words,

Comparator

.

reverseOrder

(

)

)

;

// Sort in reverse order by length

Collections

.

sort

(

words,

Comparator

.

comparingInt

(

String

::

length

)

.

reversed

(

)

)

;


Shuffling

Collections.shuffle() uses the Fisher-Yates algorithm to randomly shuffle the order of elements in a List.

Original list A B C D shuffle() After shuffling (random) C D A B ? ? ? Results differ each time it is executed shuffle(list, new Random(42)) can take a fixed seed to make the shuffle result reproducible

Example

import

java.util.ArrayList

;

import

java.util.Collections

;

import

java.util.List

;

public

class

ShuffleExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        List

<
Integer
numbers
=
new
ArrayList
<>
(
)

;

       

for

(

int

i

=

1

;

i

<=

10

;

i

++

)

{

            numbers.

add

(

i

)

;

       

}

       

System

.

out

.

println

(

"Original list: "

numbers

)

;

       

// Randomly shuffle the order

       

Collections

.

shuffle

(

numbers

)

;

       

System

.

out

.

println

(

"First shuffle: "

numbers

)

;

       

Collections

.

shuffle

(

numbers

)

;

       

System

.

out

.

println

(

"Second shuffle: "

numbers

)

;

   

}

}

Output result:


原始列表: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
第一次混排: [7, 3, 9, 1, 5, 10, 8, 2, 4, 6]
第二次混排: [4, 10, 1, 8, 6, 3, 2, 9, 5, 7]

Binary Search

Collections.binarySearch() uses the binary search algorithm in an ordered List to locate the target element.

The time complexity is O(log n), far better than the O(n) of linear traversal.

Important prerequisite: The List must already be sorted in ascending order, otherwise the result is uncertain.

Example

import

java.util.ArrayList

;

import

java.util.Collections

;

import

java.util.List

;

public

class

BinarySearchExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        List

<
Integer
numbers
=
new
ArrayList
<>
(
)

;

        numbers.

add

(

10

)

;

        numbers.

add

(

30

)

;

        numbers.

add

(

20

)

;

        numbers.

add

(

50

)

;

        numbers.

add

(

40

)

;

       

// Must sort first

       

Collections

.

sort

(

numbers

)

;

       

System

.

out

.

println

(

"Sorted list: "

numbers

)

;

       

// Binary search: return value is the index (>= 0 means found)

       

int

index

=

Collections

.

binarySearch

(

numbers,

30

)

;

       

System

.

out

.

println

(

"Index position of 30: "

index

)

;

       

// Search for a non-existent element: returns a negative value = -(insertion point) - 1

       

int

notFound

=

Collections

.

binarySearch

(

numbers,

25

)

;

       

System

.

out

.

println

(

"Return value of 25 (not found): "

notFound

)

;

       

// Insertion point = -(notFound + 1) = 2, should be inserted at index 2

   

}

}

Output result:


排序后列表: [10, 20, 30, 40, 50]
30 的索引位置: 2
25 的返回值(不存在): -3

When binarySearch() cannot find an element, it returns a negative value, with the formula -(insertion point) - 1. The insertion point is the index where the element would be located if it existed. The cleverness of this design is: if the element exists, a non-negative index is returned; if it does not exist, a negative value is necessarily returned, with no ambiguity.


Maximum and Minimum Values

Collections.max() and Collections.min() return the maximum/minimum element in the collection according to natural order or a specified comparator.

Example

import

java.util.ArrayList

;

import

java.util.Collections

;

import

java.util.Comparator

;

import

java.util.List

;

public

class

MaxMinExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        List

<
String
words
=
new
ArrayList
<>
(
)

;

        words.

add

(

"runoob"

)

;

        words.

add

(

"algorithm"

)

;

        words.

add

(

"java"

)

;

        words.

add

(

"code"

)

;

       

// Get max and min by natural order (lexicographic)

       

String

maxWord

=

Collections

.

max

(

words

)

;

       

String

minWord

=

Collections

.

min

(

words

)

;

       

System

.

out

.

println

(

"Lexicographic max: "

maxWord

)

;

       

System

.

out

.

println

(

"Lexicographic min: "

minWord

)

;

       

// Get max and min by string length

       

String

longest

=

Collections

.

max

(

words,

           

Comparator

.

comparingInt

(

String

::

length

)

)

;

       

String

shortest

=

Collections

.

min

(

words,

           

Comparator

.

comparingInt

(

String

::

length

)

)

;

       

System

.

out

.

println

(

"Longest: "

longest

)

;

       

System

.

out

.

println

(

"Shortest: "

shortest

)

;

   

}

}

Output result:


字典序最大: runoob
字典序最小: algorithm
长度最长: algorithm
长度最短: code

Frequency Count and Disjoint Check

Collections.frequency() counts the number of times a specified element appears in the collection.

Collections.disjoint() determines whether two collections have no common elements at all.

Example

import

java.util.ArrayList

;

import

java.util.Collections

;

import

java.util.List

;

public

class

FrequencyDisjointExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        List

<
String
items
=
new
ArrayList
<>
(
)

;

        items.

add

(

"runoob"

)

;

        items.

add

(

"java"

)

;

        items.

add

(

"runoob"

)

;

        items.

add

(

"python"

)

;

        items.

add

(

"runoob"

)

;

       

// Count the occurrences of "runoob"

       

int

count

=

Collections

.

frequency

(

items,

"runoob"

)

;

       

System

.

out

.

println

(

"Occurrences of "runoob": "

count

)

;

       

// Determine whether two collections are disjoint

        List

<
String
groupA
=
new
ArrayList
<>
(
)

;

        groupA.

add

(

"java"

)

;

        groupA.

add

(

"python"

)

;

        List

<
String
groupB
=
new
ArrayList
<>
(
)

;

        groupB.

add

(

"C++"

)

;

        groupB.

add

(

"go"

)

;

       

boolean

noCommon

=

Collections

.

disjoint

(

groupA, groupB

)

;

       

System

.

out

.

println

(

"groupA and groupB disjoint: "

noCommon

)

;

   

}

}

Output result:


"runoob" 出现次数: 3
groupA 与 groupB 不相交: true

Immutable Collections and Thread-Safe Wrappers

Collections provides methods to wrap ordinary collections as immutable or thread-safe collections.

Immutable Collection (Unmodifiable)

Calling Collections.unmodifiableList() and similar methods can create a read-only view.

Any modification operation throws an UnsupportedOperationException.

Thread-Safe Collection (Synchronized)

Calling Collections.synchronizedList() and similar methods can create a thread-safe wrapper.

Single method calls on these collections in a multi-threaded environment are safe, but compound operations still require external synchronization.

Example

import

java.util.ArrayList

;

import

java.util.Collections

;

import

java.util.List

;

public

class

WrapperExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        List

<
String
original
=
new
ArrayList
<>
(
)

;

        original.

add

(

"runoob"

)

;

        original.

add

(

"java"

)

;

       

// Create an immutable view

        List

<
String
readOnly
=
Collections

.

unmodifiableList

(

original

)

;

       

System

.

out

.

println

(

"Immutable view: "

readOnly

)

;

       

// readOnly.add("error"); // Executing this throws an exception

       

// After the original list is modified, the immutable view also reflects the change

        original.

add

(

"python"

)

;

       

System

.

out

.

println

(

"After original modified: "

readOnly

)

;

       

// Create a thread-safe wrapper

        List

<
String
syncList
=
Collections

.

synchronizedList

(

           

new

ArrayList

<>

(

)

)

;

        syncList.

add

(

"thread-safe"

)

;

       

// Manual synchronization required when iterating

       

synchronized

(

syncList

)

{

           

for

(

String

item

:

syncList

)

{

               

System

.

out

.

println

(

item

)

;

           

}

       

}

   

}

}

Output result:


不可变视图: [runoob, java]
原始修改后: [runoob, java, python]
thread-safe

An immutable view only prevents modifying the collection through that view; the underlying collection is still mutable. If you need a truly immutable collection, use the Java 9+ List.of(), Set.of() and similar methods.


Summary of Common Algorithm Operations

The following summarizes the calling methods and time complexity of commonly used algorithms in Collections:

Operation Method Call Time Complexity Precondition
Sorting Collections.sort(list) O(n log n) Element implements Comparable
Custom sorting Collections.sort(list, comp) O(n log n) Provide a Comparator
Reverse Collections.reverse(list) O(n) None
Shuffle Collections.shuffle(list) O(n) None
Binary Search Collections.binarySearch(list, key) O(log n) List already sorted
Fill Collections.fill(list, obj) O(n) None
Copy Collections.copy(dest, src) O(n) dest.size() >= src.size()
Maximum value Collections.max(coll) O(n) Element implements Comparable
Minimum value Collections.min(coll) O(n) Element implements Comparable
Frequency Count Collections.frequency(coll, obj) O(n) None
Swap elements Collections.swap(list, i, j) O(1) Index valid
Rotate Collections.rotate(list, distance) O(n) None

Notes

binarySearch() must be called on a sorted list; the result on an unsorted list is undefined. If the list contains duplicate elements, it is not guaranteed which one is found.

The wrapper returned by synchronizedXxx() only guarantees atomicity at the level of a single method call. Compound operations (such as if(!list.contains(x)) list.add(x)) still require an external synchronized block.

Difference between sort() and List.sort():

After Java 8, the List interface added the sort(Comparator) default method.

list.sort(null) sorts in natural order, equivalent to Collections.sort(list).

Both have the same underlying implementation, but list.sort() is more concise.

Performance Comparison Suggestions:

For small data volumes (< 100 elements), the performance differences among algorithms are negligible.

For large data volumes, binarySearch() is far superior to the linear search of indexOf().

When frequent searching is needed, consider using HashSet instead of List, with a query complexity of O(1).