.replaceAll()
Published Jun 24, 2024
Contribute to Docs
The .replaceAll()
method in Java is used for transforming all elements of a list according to a specified unary operation, effectively updating each element in place with the result of the operation applied to it. It does not return any value.
Syntax
arrayList.replaceAll(UnaryOperator<E> operator)
arrayList
: TheArrayList
on which the.replaceAll()
method is called.operator
: Represents the unary operator that will be applied to each element in theArrayList
.
Example
In this example, an ArrayList
named cities
is created and populated with city names using .add()
. Then, .replaceAll()
is used to transform all city names to lowercase, updating each element in place.
import java.util.ArrayList;public class Main {public static void main(String[] args) {// Create an ArrayList for different citiesArrayList<String> cities = new ArrayList<>();// Add cities to the ArrayListcities.add("STOCKHOLM");cities.add("LONDON");cities.add("PARIS");cities.add("BERLIN");System.out.println("Cities in uppercase: " + cities);// Call replaceAll() on ArrayList to make every String element lowercasecities.replaceAll(String::toLowerCase);System.out.println("Updated cities in lowercase: " + cities);}}
The output for this code would look like this:
Cities in uppercase: [STOCKHOLM, LONDON, PARIS, BERLIN]Updated cities in lowercase: [stockholm, london, paris, berlin]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours