Close

Java - How to modify all elements of a List?

[Last Updated: Apr 29, 2017]

Java Collections Java 

Using ListIterator

java.util.ListIterator allows to transverse the list in both directions. We can do that by using hasNext(), next(), previous() and hasPrevious() methods. It also allows to replace the current element via set() method. This example shows how to replace all elements after a modification:

public class ListReplaceAllExample {
  public static void main(String[] args) {
      List<String> list = Arrays.asList("one", "two", "three");
      System.out.println("before modification: "+list);
      ListIterator<String> iterator = list.listIterator();
      while (iterator.hasNext()){
          String s = iterator.next();
          iterator.set(s.toUpperCase());
      }

      System.out.println("after modification: "+list);
  }
}

Output

before modification: [one, two, three]
after modification: [ONE, TWO, THREE]

Using List.ReplaceAll

Java 8 added a new method void replaceAll(UnaryOperator&tlE> operator) in java.util.List class, which can do the same thing:

public class ListReplaceAllExample2 {
  public static void main(String[] args) {
      List<String> list = Arrays.asList("one", "two", "three");
      System.out.println("before modification: "+list);
      list.replaceAll(s -> s.toUpperCase());
      System.out.println("after modification: "+list);
  }
}

Output

before modification: [one, two, three]
after modification: [ONE, TWO, THREE]

See Also