Home » Java programming language

Java Collections replaceAll() Method with Example

Collections Class replaceAll() method: Here, we are going to learn about the replaceAll() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 04, 2020

Collections Class replaceAll() method

  • replaceAll() method is available in java.util package.
  • replaceAll() method is used to replace all occurrences of the given old element (old_ele) that exists in a List(l) with the given new element (new_ele).
  • replaceAll() method is a static method, so it is accessible with the class name and if we try to access this method with the class object then we will not get an error.
  • replaceAll() method may throw an exception at the time of replacing the old element with the new element in a list.
    UnsupportedOperationException: This exception may throw when the given List(l) un-support set operation.

Syntax:

    public static boolean replaceAll(List l, Type old_ele, Type new_ele);

Parameter(s):

  • List l – represents the list in which replacement of the given old_ele is to occur.
  • Type old_ele – represents the old element to be replaced from the given list.
  • Type new_ele – represents the new element with which old element is to be replaced in the given list.

Return value:

The return type of this method is boolean, it returns true when the given old element (old_ele) is no more exists in the given list otherwise it returns false.

Example:

// Java program is to demonstrate the example of
// replaceAll(List l, Type old_ele, Type new_ele)
// method of Collections

import java.util.*;

public class ReplaceAllOfCollections {
    public static void main(String args[]) {
        // Here, we are creating list object
        List < Integer > l = new ArrayList < Integer > ();

        // By using add()method is to add
        // objects in a list 
        l.add(10);
        l.add(20);
        l.add(30);
        l.add(40);
        l.add(50);
        l.add(30);

        // Display list before replaceAll()
        System.out.println("List: " + l);

        // By using replaceAll() method is to
        // replace all 30 with 300 in a list
        Collections.replaceAll(l, 30, 300);

        // Display list after replaceAll()
        System.out.println("Collections.replaceAll(l,30,300): " + l);
    }
}

Output

List: [10, 20, 30, 40, 50, 30]
Collections.replaceAll(l,30,300): [10, 20, 300, 40, 50, 300]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.