Open In App

Java Program to Replace an Element in a List

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

List in Java provides a way to store the ordered collection. The list Interface provides various methods to add, delete, or replace items in the List. In this article, we will learn about how we could replace an element in the list in Java.

Methods to Replace an Element in a List

There are 3 ways to replace an element in the list as listed which will be later revealed as follows:

  1. set() method by indexes(in-built method in Java).
  2. replaceAll() method by putting some conditions.
  3. ListIterator() method

We will discuss all the methods one by one.

1. Using set() method by indexes(in-built method)

In this example, we are using the set() method of List Collection which is the default method. So basically by using this in-built method, we are replacing the element with the help of an index.

Syntax:

public Object set(int index,Object element);

Parameters:

  • int index: It refers to the position of the element that needs to be replaced in the List.
  • Object element: It is the new element by which the existing element needs to be replaced.

Below is the implementation of the above method:

Java




// Java Program to implement
// Set in replace an
// Element in a list
import java.io.*;
import java.util.ArrayList;
  
// Driver Class
class GFG {
    // Main function
    public static void main(String[] args)
    {
        // ArrayList Declared
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        list1.add(100);
        list1.add(2);
        list1.add(300);
        list1.add(400);
  
        System.out.println("Original List: " + list1);
  
        // Replaces the element in the specified index by
        // the specified value passed in the method
        list1.set(1, 200);
  
        System.out.println(
            "Modified List after replacement: " + list1);
    }
}


Output

Original List: [100, 2, 300, 400]
Modified List after replacement: [100, 200, 300, 400]



2. Using replaceAll() method by putting some conditions

In this example, we are using the replaceAll() method of ArrayList and we need to apply some condition so that only the valid element that we want to replace will be replaced.

Syntax:

arrayList.replaceAll(UnaryOperator<E> the );

Parameter:

  • operator: operation to be applied for every element.

Explanation:

So in this example, our original list contains [1000,2000,5000,4000] and our task is to replace 5000 with 3000. So we will write a condition inside replaceAll() method to replace the element.

 list1.replaceAll(element-> element==5000 ? 3000 : element);

So the line written above runs for every element and checks if the element is equal to 5000 then it returns 3000 otherwise it returns the same element. So by this line our original list containing 5000 will be replaced by 3000 and those elements which are not equal to 5000 remains as it is.

Below is the implementation of the above method:

Java




// Java Program to implement
// ReplaceAll to replace an 
// Element in a list
import java.io.*;
import java.util.ArrayList;
  
// Driver Class
class GFG {
    // main function
    public static void main(String[] args)
    {
         // ArrayList Declared
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        list1.add(1000);
        list1.add(2000);
        list1.add(5000);
        list1.add(4000);
  
        System.out.println("Original List: " + list1);
  
        // Replaces the element in the specified index by
        // the specified value passed in the method
        list1.replaceAll(
            element -> element == 5000 ? 3000 : element);
  
        System.out.println(
            "Modified List after replacement: " + list1);
    }
}


Output

Original List: [1000, 2000, 5000, 4000]
Modified List after replacement: [1000, 2000, 3000, 4000]



3. Using the ListIterator() method

Here in this example, Our original list contains [“Welcome”, “to”, “GFG”, “Learn”, “here”]. So our task is to replace “GFG” at position 3 with “Geeks For Geeks”.

Before that, ListIterator has several functions we have used in our code that we need to discuss before we move towards an example. listIterator(): It returns a list iterator over the elements in the list.

So in this example, we know “GFG” is at position 3. So, whenever our position becomes 3 we will replace the string(i.e. “GFG” ) with “Geeks For Geeks” using set() method of list iterator discussed above.

Below is the implementation of the above method:

Java




// Java Program to demonstrate
// ListIterator to replace an 
// Element in a list
import java.io.*;
import java.util.ArrayList;
import java.util.ListIterator;
  
// Driver Class
class GFG {
      // main function
    public static void main(String[] args)
    {
          // Declaring ArrayList
        ArrayList<String> list1 = new ArrayList<String>();
        list1.add("Welcome");
        list1.add("to");
        list1.add("GFG");
        list1.add("Learn");
        list1.add("here");
  
        System.out.println("Original List : " + list1);
  
          // Iterator
        ListIterator<String> listIterator
            = list1.listIterator();
  
        while (listIterator.hasNext()) {
            int position = listIterator.nextIndex();
            
              // ListIterator used for replacing the 
              // value
            if (position == 3) {
                listIterator.set("Geeks For Geeks");
            }
            listIterator.next();
        }
  
        System.out.println("Modified List : " + list1);
    }
}


Output

Original List : [Welcome, to, GFG, Learn, here]
Modified List : [Welcome, to, Geeks For Geeks, Learn, here]





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads