HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Collections Framework / Java ArrayList / ArrayList replaceAll() method example

ArrayList replaceAll() method example

ArrayList replaceAll() retains only the elements in this list that are contained in the specified method argument collection. Rest all elements are removed from the list. This method is exact opposite to removeAll() method.

1. ArrayList replaceAll() method

The replaceAll() method takes single argument of type UnaryOperator. The UnaryOperator interface is a functional interface that has a single abstract method named apply that returns a result of the same object type as the operand.

We have seen UnaryOperator in action in usually lambda expressions taking a single argument in form of 'x-> do something with x'.

public void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final int size = this.size;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        elementData[i] = operator.apply((E) elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

Method parameter – UnaryOperator expression.
Method returns – void.
Method throws – ConcurrentModificationException if list is modified while replaceAll() method is not finished.

2. ArrayList replaceAll() example

Java program to use replaceAll() method to transform all the elements of an arraylist using a lambda expression.

2.1. Inline lambda expression

We can use the inline lambda expressions in case the we have to execute only single statement.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
        
        System.out.println(alphabets);
        
        alphabets.replaceAll( e -> e.toLowerCase() );  
        
        System.out.println(alphabets);
    }
}

Program output.

[A, B, C, D, E]
[a, b, c, d, e]

2.2. Custom UnaryOperator implemetation

Create a new class which implements UnaryOperator to executed a more complex logic on each element of arraylist.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.UnaryOperator;

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
        
        System.out.println(alphabets);
        
        alphabets.replaceAll( new MyOperator() );  
        
        System.out.println(alphabets);
    }
}

class MyOperator implements UnaryOperator<String> 
{
    @Override
    public String apply(String t) {
        return t.toLowerCase();
    }
}

Program output.

[A, B, C, D, E]
[a, b, c, d, e]

That’s all for the ArrayList replaceAll() method in Java.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

ArrayList Methods

  • ArrayList – Introduction
  • ArrayList – add()
  • ArrayList – addAll()
  • ArrayList – clear()
  • ArrayList – clone()
  • ArrayList – contains()
  • ArrayList – ensureCapacity()
  • ArrayList – forEach()
  • ArrayList – get()
  • Arraylist – indexOf()
  • Arraylist – lastIndexOf()
  • ArrayList – listIterator()
  • ArrayList – remove()
  • ArrayList – removeAll()
  • ArrayList – removeIf()
  • ArrayList – retainAll()
  • ArrayList – sort()
  • ArrayList – spliterator()
  • ArrayList – subList()
  • ArrayList – toArray()

ArrayList Examples

  • ArrayList – Initialize arraylist
  • ArrayList – Iteration
  • ArrayList – Add/replace element
  • ArrayList – Add multiple elements
  • ArrayList – Check empty list
  • ArrayList – Remove element
  • ArrayList – Replace element
  • ArrayList – Empty arraylist
  • ArrayList – Synchronized arraylist
  • ArrayList – Compare two lists
  • ArrayList – Remove duplicates
  • ArrayList – Merge two lists
  • ArrayList – Serialization
  • ArrayList – Swap two elements
  • Convert ArrayList to Array
  • Convert Array to ArrayList
  • Convert HashSet to ArrayList
  • Convert LinkedList to ArrayList
  • Convert Vector to ArrayList
  • ArrayList vs LinkedList
  • ArrayList vs Vector

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)