Java HashSet retainAll() Method
Method Overview
retainAll() is the Java HashSet class, an important method used to retain the elements in the collection that are the same as those in the specified collection, in other words, to compute the intersection of the two collections.
Method Syntax
Example
public
boolean
retainAll
(
Collection
c
)
Method parameters
Collection> c: The collection containing the elements to retain- Return value: If
HashSetchanged due to the call, returntrue; otherwise, returnsfalse
How It Works
Basic Functionality
retainAll() method modifies the current HashSetso that it only retains the elements that are the same as those in the specified collection c . All elements not in the specified collection c will be removed from the current HashSet .
Algorithm Complexity
The time complexity of this method is usually O(n), where n is the size of the collection, because it needs to check whether each element in the current collection exists in the specified collection.
Usage examples
Example 1: Basic usage
Example
import
java.util.HashSet
;
public
class
RetainAllExample
{
public
static
void
main
(
String
[
]
args
)
{
// Create the first HashSet
HashSet
<
String
set1
=
new
HashSet
<>
(
);
set1.
add
(
"Apple"
)
;
set1.
add
(
"Banana"
)
;
set1.
add
(
"Orange"
)
;
// Create the second HashSet
HashSet
<
String
set2
=
new
HashSet
<>
(
);
set2.
add
(
"Banana"
)
;
set2.
add
(
"Grape"
)
;
// Retain the elements in set1 that are the same as those in set2
boolean
changed
=
set1.
retainAll
(
set2
)
;
System
.
out
.
println
(
"Was set1 modified: "
changed
)
;
// Output: true
System
.
out
.
println
(
"set1 content after retention: "
set1
)
;
// Output: [Banana]
}
}
Example 2: Case with No Common Elements
Example
import
java.util.HashSet
;
public
class
NoCommonElements
{
public
static
void
main
(
String
[
]
args
)
{
HashSet
<
Integer
numbers1
=
new
HashSet
<>
(
);
numbers1.
add
(
1
)
;
numbers1.
add
(
2
)
;
numbers1.
add
(
3
)
;
HashSet
<
Integer
numbers2
=
new
HashSet
<>
(
);
numbers2.
add
(
4
)
;
numbers2.
add
(
5
)
;
boolean
changed
=
numbers1.
retainAll
(
numbers2
)
;
System
.
out
.
println
(
"Was the collection modified: "
changed
)
;
// Output: true
System
.
out
.
println
(
"numbers1 content after retention: "
numbers1
)
;
// Output: []
}
}
Notes
1. Collection Modification
- If calling
retainAll()results in no change to the collection (i.e., it is already the intersection of the two collections), the method will returnfalse - If the specified collection
cis empty, the current collection will be cleared
2. Concurrent Modification
If calling while iterating over the collection retainAll() method, a may be thrown ConcurrentModificationException. You should complete collection modification operations before iterating.
3. Null Value Handling
- If the current collection allows null values but the parameter collection does not, calling
retainAll()will remove the null values - If the parameter collection is null, a will be thrown
NullPointerException
Practical Application Scenarios
1. Data Filtering
When you need to filter a subset that meets specific conditions from a large data set, you can use retainAll() method.
2. Access Control
In a permission system, you can use this method to find the intersection of all permissions a user has and the permissions required by a certain role.
3. Data Analysis
In data analysis, find the elements common to two data sets.
Comparison with Other Methods
| Method | Function | Whether the Original Collection Is Modified | Meaning of the Return Value |
|---|---|---|---|
retainAll() |
Retain the elements that are the same as those in the specified collection | Is | Whether the collection is modified |
removeAll() |
Remove the elements that are the same as those in the specified collection | Is | Whether the collection is modified |
containsAll() |
Check whether all elements of the specified collection are contained | No | Whether all are contained |
addAll() |
Add all elements of the specified collection | Is | Whether the collection is modified |
Performance Optimization Suggestions
- If you frequently perform set intersection operations, consider using a library specifically optimized for set operations
- For large collections, you can first convert the smaller collection to
HashSetto improve lookup efficiency - Using in a multi-threaded environment
Collections.synchronizedSet()Wrapping the Collection
Summary
HashSet 's retainAll() method is a powerful collection operation tool that can conveniently implement set intersection. Understanding its working principle and characteristics can help developers handle collection data more efficiently. In actual development, you should choose the appropriate collection operation method based on specific needs and pay attention to its performance impact and thread safety.
Java HashSet