Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java list replace/fill elements


Sometimes we want on Java List replace/fill all/selected elements. It can be done manually, but much better way is to reuse Java Collections API. See how!


There are two cases:

  1. Replace all occurrences of element with the new value.
  2. Replace all elements in a list with the new value.

The following Java example leverages Java Collections API to do the job:


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

public class CollectionsFill {

    public static void main(String[] args) {


    private static void replaceSelectedElement() {
        List<String> items = Arrays.asList("a", "b", "c", "b");
        System.out.println("Original: " + items);

        Collections.replaceAll(items, "b", "B");
        System.out.println("Updated: " + items);

    private static void replaceAllElementsWithOne() {
        List<String> languages = new LinkedList<>();

        System.out.println("\nLanguages: " + languages);

        Collections.fill(languages, "Esperanto");
        System.out.println("Updated empty: " + languages);

        Collections.addAll(languages, "English", "Espanol");
        System.out.println("Languages: " + languages);

        Collections.fill(languages, "Esperanto");
        System.out.println("Updated: " + languages);

In the first method (replaceSelectedElement) we use Collections.replaceAll(List<T>, T from, T to) to replace all occurrences of selected element with the new value.

In the replaceAllElementsWithOne method we use Collections.fill(List<T>, T obj) to replace all elements in the list with the new value.

Of course, in both cases the list implementations must support set operation, else UnsupportedOperationException will be thrown!

And here’s the result:

Original: [a, b, c, b]
Updated: [a, B, c, B]

Languages: []
Updated empty: []
Languages: [English, Espanol]
Updated: [Esperanto, Esperanto]

As you can see Collections.fill() replaces only existing elements, so can’t be used to create a new List with initial values. ;-)

Share with the World!