Replace an element at given index of a List with new element in Java

Here, we are going to learn how to replace an element at given index of a list with a new element in java?
Submitted by IncludeHelp, on October 10, 2018

Given a list of the integers and we have to replace it an element from specified index with a new element in java.

To replace an element in the list - we use List.set() method.

List.set() method

List.set() method replaces an existing element at given index with new element and returns the old object/element.

Syntax:

    Object List.set(index, new_object);

Example:

    Input:
    List = [10, 20, 30, 40, 50]
    Index =1 
    new_element = 1000

    Output:
    Updated list =[10, 1000, 30, 40, 50]

Program:

import java.util.*;

public class ListExample {
  public static void main(String[] args) {
    //creating a list of integers
    List < Integer > int_list = new ArrayList < Integer > ();

    //adding some of the elements 
    int_list.add(10);
    int_list.add(20);
    int_list.add(30);
    int_list.add(40);
    int_list.add(50);

    //replace elements
    int old_ele, new_ele, index;
    index = 0;
    new_ele = 12;
    old_ele = int_list.set(index, new_ele);
    System.out.println(old_ele + " is replace with " + new_ele);

    index = 2;
    new_ele = 24;
    old_ele = int_list.set(index, new_ele);
    System.out.println(old_ele + " is replace with " + new_ele);

    //printing updated list 
    System.out.println("updated list: " + int_list);
  }
};

Output

10 is replace with 12
30 is replace with 24
updated list: [12, 20, 24, 40, 50]

Another Example: Replace all elements of EVEN indexes with 0 and ODD indexes by 1

Example:

    Input:
    List = [10, 20, 30, 40, 50]

    Output:
    Updated list =[0, 1, 0, 1, 0]

Program:

import java.util.*;

public class ListExample {
  public static void main(String[] args) {
    //creating a list of integers
    List < Integer > int_list = new ArrayList < Integer > ();

    //adding some of the elements 
    int_list.add(10);
    int_list.add(20);
    int_list.add(30);
    int_list.add(40);
    int_list.add(50);

    System.out.println("len: " + int_list.size());
    //replace elements 
    for (int i = 0; i < int_list.size(); i++) {
      if (i % 2 == 0)
        int_list.set(i, 0);
      else
        int_list.set(i, 1);
    }

    //printing updated list 
    System.out.println("updated list: " + int_list);
  }
};

Output

len: 5
updated list: [0, 1, 0, 1, 0]

Java List Programs »





Comments and Discussions!

Load comments ↻





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