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

Java ArrayList replaceAll() Method · Private Archive

Java ArrayList replaceAll() Method · Private Archive

Java ArrayList Java ArrayList

Java ArrayList replaceAll() Method

The replaceAll() method is used to replace every element in the array with the given operation content.


arraylist.replaceAll(UnaryOperator operator)

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

Parameter Description:

Return Value

No value is returned.

Example

operator - the element or a series of operations to be replaced into the dynamic array

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 replaceAll() method:

        sites.

replaceAll

(

e

->

e.

toUpperCase

(

)

)

;

       

System

.

out

.

println

(

// Change all elements to uppercase

sites

)

;

   

}

}

The output of the above program is:


ArrayList : [Google, Runoob, Taobao]
更新后的 ArrayList: [GOOGLE, RUNOOB, TAOBAO]

"Updated ArrayList: "

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a dynamic array

        ArrayList

<

Integer

numbers

=

new

ArrayList

<>

(

)

;

       

// Add elements to the array

        numbers.

add

(

1

)

;

        numbers.

add

(

2

)

;

        numbers.

add

(

3

)

;

       

System

.

out

.

println

(

"ArrayList: "

numbers

)

;

       

Multiply all elements in the dynamic array by 2:

        numbers.

replaceAll

(

e

->

e

2

)

;;

       

System

.

out

.

println

(

// Change all elements to uppercase

numbers

)

;

   

}

}

The output of the above program is:

ArrayList: [1, 2, 3]
更新后的 ArrayList: [2, 4, 6]

// Multiply all elements by 2

Note this line:

numbers.replaceAll(e -> e * 2);

Java ArrayList Java ArrayList