Java 实例 - List 元素替换


以下实例演示了如何使用 Collections 类的 replaceAll() 来替换List中所有的指定元素:

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. import java.util.*;
  7.  
  8. public class Main {
  9. public static void main(String[] args) {
  10. List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
  11. System.out.println("List :"+list);
  12. Collections.replaceAll(list, "one", "hundread");
  13. System.out.println("replaceAll: " + list);
  14. }
  15. }

以上代码运行输出结果为:

  1. List :[one, Two, three, Four, five, six, one, three, Four]
  2. replaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]