Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace elements in a list with another

Tags:

java

list

How do I replace elements in a list with another?

For example I want all two to become one?

like image 578
chaotictranquility Avatar asked Jul 23 '10 11:07

chaotictranquility


People also ask

Does replace () work on lists?

You can replace items in a Python list using list indexing, a list comprehension, or a for loop. If you want to replace one value in a list, the indexing syntax is most appropriate.

How do you replace multiple elements in a list in Python?

One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.

How do you use replace in a list?

Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .

How do you replace a word in a list with another in Python?

Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.


1 Answers

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]
like image 52
polygenelubricants Avatar answered Oct 16 '22 06:10

polygenelubricants