Java Example – Removing a Specified Element from a Collection
The following example demonstrates how to use the collection.remove() method of the Collection class to remove a specified element from the collection:
Main.java File
import
java
.
util
.*;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
System
.
out
.
println
(
"
Collection example!
\n
"
)
;
int
size
;
HashSet
collection
=
new
HashSet
(
)
;
String
str1
=
"
Yellow
"
,
str2
=
"
White
"
,
str3
=
"
Green
"
,
str4
=
"
Blue
"
;
Iterator
iterator
;
collection
.
add
(
str1
)
;
collection
.
add
(
str2
)
;
collection
.
add
(
str3
)
;
collection
.
add
(
str4
)
;
System
.
out
.
(
"
Collection data:
"
)
;
iterator
=
collection
.
iterator
(
)
;
while
(
iterator
.
hasNext
(
)
)
{
System
.
out
.
(
iterator
.
next
(
)
"
"
)
;
}
System
.
out
.
println
(
)
;
collection
.
remove
(
str2
)
;
System
.
out
.
println
(
"
After deletion [
"
str2
"
]
\n
"
)
;
System
.
out
.
(
"
Now the collection data is:
"
)
;
iterator
=
collection
.
iterator
(
)
;
while
(
iterator
.
hasNext
(
)
)
{
System
.
out
.
(
iterator
.
next
(
)
"
"
)
;
}
System
.
out
.
println
(
)
;
size
=
collection
.
size
(
)
;
System
.
out
.
println
(
"
Collection size:
"
size
"
\n
"
)
;
}
}
The output of the above code is:
集合实例!
集合数据: White Yellow Blue Green
删除之后 [White]
现在集合的数据是: Yellow Blue Green
集合大小: 3
Java Examples