Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Replace List Elements


As we have seen the implementations of a List are :

  1. ArrayList

  2. LinkedList


Let us see the ArrayList implementation first.


Change/Replace an Item in an ArrayList using index


Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to replace the name Kriti with a new name Paul.


Example :



import java.util.ArrayList;
import java.util.List;

public class MyApplication {
    public static void main(String[] args) {

        List x = new ArrayList<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        x.set(1,"Paul");

        for (String data : x) {
            System.out.println(data);
        }
    }
}


Output :



  Mohan
  Paul
  Salim

So, in the above code we have created an ArrayList x.


List x = new ArrayList<>();

Now, let us see, how the values are positioned in the List

Spring_Boot

Now, if we see the above diagram, Kriti resides at position/index 1. So, what we do is, just replace the position/index 1 (i.e. x.set(1,"Paul")) with the new name Paul, using the set() method.


x.set(1,"Paul");
Spring_Boot


And we get the below output,

Output :



  Mohan
  Paul
  Salim

Next, let us see the implementation using LinkedList. It is exactly similar to ArrayList.


Change/Replace an Item in an ArrayList using index


Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to replace the name Kriti with a new name Paul.


Example :



import java.util.LinkedList;
import java.util.List;

public class MyApplication {
    public static void main(String[] args) {

        List x = new LinkedList<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        x.set(1,"Paul");

        for (String data : x) {
            System.out.println(data);
        }
    }
}


Output :



  Mohan
  Paul
  Salim