We are moved to new domain
Click -> www.ehowtonow.com
Saturday, 30 May 2015

How to replace the element from List

Following example shows how to replace all the occurrence of element with another element using Collections.replaceAll(list, oldVal, newVal) method in Java.

<String> boolean java.util.Collections.replaceAll(List<String> list, String oldVal, String newVal)
replaceAll
public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)
Replaces all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in list such that (oldVal==null ? e==null : oldVal.equals(e)). (This method has no effect on the size of the list.)
Parameters:
list - the list in which replacement is to occur.
oldVal - the old value to be replaced.
newVal - the new value with which oldVal is to be replaced.
Returns:
true if list contained one or more elements e such that (oldVal==null ? e==null : oldVal.equals(e)).
Throws:
UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation.

Sample Program
ReplaceElementInList.java
package com.javatutorialcorner.collection;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReplaceElementInList {

 public static void main(String[] args) {
  String[] nameArray = new String[] { "Spring", "Struts", "Hibernate",
    "Webservice", "SOAP Webservice", "RESTful Webservice" };
  List<String> nameList = Arrays.asList(nameArray);
  System.out.println("*********** Before Replace ************");
  for (String name : nameList) {
   System.out.println(name);
  }

  System.out.println("*********** After Replace ************");

  Collections.replaceAll(nameList, "Spring", "Spring Framework");
  for (String name : nameList) {
   System.out.println(name);
  }

 }

}


Result
The above code will produce the following output.
*********** Before Replace ************
Spring
Struts
Hibernate
Webservice
SOAP Webservice
RESTful Webservice
*********** After Replace ************
Spring Framework
Struts
Hibernate
Webservice
SOAP Webservice
RESTful Webservice

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to replace the element from List Rating: 5 Reviewed By: eHowToNow