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

Java ArrayList removeIf() Method · Private Archive

Java ArrayList removeIf() Method · Private Archive

Java ArrayList Java ArrayList

Java ArrayList removeIf() Method

The removeIf() method is used to delete all array elements that satisfy a specific condition.


arraylist.removeIf(Predicate filter)

**Note:** arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

filter - the filter that determines whether an element should be deleted

Example

Returns true if an element is deleted.

Example

import

java.util.*

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a dynamic array

        ArrayList

<

String

sites

=

new

ArrayList

<>

(

)

;

       

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

       

System

.

out

.

println

(

"ArrayList : "

sites

)

;

       

The following example demonstrates the use of the removeIf() method:

        sites.

removeIf

(

e

->

e.

contains

(

"Tao"

)

)

;;

       

System

.

out

.

println

(

// Delete elements whose name contains Tao

sites

)

;

   

}

}

The output of the above program is:


ArrayList : [Google, Runoob, Taobao]
删除后的 ArrayList: [Google, Runoob]

"ArrayList after deletion: " In the example above, we usedJava String contains() Method

to check whether the element contains "Tao".

removeIf() If both the e -> e.contains("land") e -> e.contains("land") returns true if the element contains "land"

If true is returned, the element is deleted.

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create an array

        ArrayList

<

Integer

numbers

=

new

ArrayList

<>

(

)

;

       

// Insert elements into the array

        numbers.

add

(

1

)

;

        numbers.

add

(

2

)

;

        numbers.

add

(

3

)

;

        numbers.

add

(

4

)

;

        numbers.

add

(

5

)

;

        numbers.

add

(

6

)

;

       

System

.

out

.

println

(

"Numbers: "

numbers

)

;

       

Deleting even-numbered elements:

        numbers.

removeIf

(

e

->

(

e

%

2

)

==

0

)

;;

       

System

.

out

.

println

(

"Odd Numbers: "

numbers

)

;

   

}

}

The output of the above program is:

Numbers: [1, 2, 3, 4, 5, 6]
Odd Numbers: [1, 3, 5]

// Delete all even elements

In the example above, we created a dynamic array named numbers.

numbers.removeIf(e -> (e % 2) == 0);

Note the expression:

e -> (e % 2) == 0) is the expression of the anonymous function lambda. It can check whether an element is divisible by 2. To learn more about anonymous functions, please visit.

removeIf() Java Lambda Expression e -> (e % 2) == 0 The method, if

Java ArrayList Java ArrayList