Java Program to Replace an Element in a List
Last Updated :
24 Oct, 2023
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:
- set() method by indexes(in-built method in Java).
- replaceAll() method by putting some conditions.
- 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);
}
}
OutputOriginal 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);
}
}
OutputOriginal 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);
}
}
OutputOriginal List : [Welcome, to, GFG, Learn, here]
Modified List : [Welcome, to, Geeks For Geeks, Learn, here]
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read