Question

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.

Was it helpful?

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.

OTHER TIPS

It doesn't sound very useful.

But try this:

import java.util.Arrays;
import java.util.List;

/**
 * http://stackoverflow.com/questions/20760578/how-do-i-replace-characters-in-every-string-in-my-list-in-java/20760659#20760659
 * Date: 12/24/13
 * Time: 7:08 AM
 */
public class SpaceEater {
    public static void main(String[] args) {
        List<String> stringList = Arrays.asList(args);
        System.out.println("before: " + stringList);
        for (int i = 0; i < stringList.size(); ++i) {
            stringList.set(i, stringList.get(i).replaceAll("\\s+", ""));
        }
        System.out.println("after : " + stringList);
    }
}

disrvptor was correct - original snippet did not alter the list. This one does.

You can try this:

No need to define new array list. Use list.set this set replaces the element at the specified position in this list with the specified element.

int i = 0;
for (String str : list)
{
  list.set(i, str.replaceAll(" ", ""));
  i++;
}

Output

for (String s : list)
{
  System.out.println(s);
}
//Thisisastring
//Thisisanotherstring

The only way I know how to do this is to iterate over the list, perform the replace operation on every object and replace the original object with the new one. This is best handled with 2 lists (source and target).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top