Java Collections replaceAll()
replaceAll() 用于将列表中一个指定值的所有出现都替换为另一个指定值。
1 语法
public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)
2 参数
list:要进行替换的列表。
oldVal:将被替换的旧值。
newVal:要替换oldVal的新值。
3 返回值
如果列表包含一个或多个元素,例如 (oldVal==null ? e==null : oldVal.equals(e)),则replaceAll() 方法返回true。
4 Collections replaceAll()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.replaceAll的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//Create vector and add element in this vector
Vector<String> vector = new Vector<String>();
vector.add("Java");
vector.add("Yiidian");
vector.add("SM1234");
vector.add("Java");
System.out.println("Initial values are :"+vector);
//Replace 'Java' with 'JavaTpont'
Collections.replaceAll(vector, "Java", "Yiidian");
System.out.println("Value after replace :"+ vector);
}
}
输出结果为:
Initial values are :[Java, Yiidian, SM1234, Java]
Value after replace :[Yiidian, Yiidian, SM1234, Yiidian]
5 Collections replaceAll()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.replaceAll的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//Create an list of String
List<String> list = Arrays.asList("one", "two", "one");
System.out.println("Original List:- "+list);
boolean b = Collections.replaceAll(list, "one", "three");
System.out.println("Boolean: "+b);
System.out.println("Value after replace:- "+list);
}
}
输出结果为:
Original List:- [one, two, one]
Boolean: true
Value after replace:- [three, two, three]
6 Collections replaceAll()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.replaceAll的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
//Create an list of integers
List<String> list = Arrays.asList("10", "20", "10", "40", "50", "10");
System.out.println("Original List: " +list);
boolean b = Collections.replaceAll(list, "10", "400");
System.out.println("Boolean: "+b);
System.out.println("Value after Replace: " +list);
}
}
输出结果为:
Original List: [10, 20, 10, 40, 50, 10]
Boolean: true
Value after Replace: [400, 20, 400, 40, 50, 400]
热门文章
优秀文章