tags:

views:

45

answers:

1

how do i replace elements in a list with another?

for example i want all "two" to become "one"?

+6  A: 

You can use:

Collections.replaceAll(list, "two", "one");

From the documentation:

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.)

The method also return a boolean to indicate whether or not any replacement was actually made.

java.util.Collections has many more static utility methods that you can use on List (e.g. sort, binarySearch, shuffle, etc).


Snippet

The following shows how Collections.replaceAll works; it also shows that you can replace to/from null as well:

    List<String> list = Arrays.asList(
        "one", "two", "three", null, "two", null, "five"
    );
    System.out.println(list);
    // [one, two, three, null, two, null, five]

    Collections.replaceAll(list, "two", "one");
    System.out.println(list);
    // [one, one, three, null, one, null, five]

    Collections.replaceAll(list, "five", null);
    System.out.println(list);
    // [one, one, three, null, one, null, null]

    Collections.replaceAll(list, null, "none");
    System.out.println(list);
    // [one, one, three, none, one, none, none]
polygenelubricants