Search code examples
javastringlistreplaceall

How do I replace characters in every string in my list in java?


I have a List of Strings, and most of them are multiple words:

"how are you"
"what time is it"

I want to remove the space from every string in this list:

"howareyou" 
"whattimeisit" 

I know of the Collections.replaceAll(list, to replace, replace with), but that only applies to Strings that are that exact value, not every instance in every String.


Solution

  • What you must is to apply the replace function to each of the string in your list.

    And as the strings are immutable you will have to create another list where string with no space will be stored.

    List<String> result = new ArrayList<>();
    
    for (String s : source) {
        result.add(s.replaceAll("\\s+", ""));
    }
    

    Immutable means that object can not be changed, it must be created new one if you want to change the state of it.

    String s = "how are you";
    
    s = s.replaceAll("\\s+", "");
    

    The function replaceAll returns the new string if you did not assign it to variable s then would still have spaces.