dhali
dhali

Reputation: 386

Getting rid of white-space for each String element in ArrayList

I am trying to get rid of all whitespace in each element of my array list.

I could loop through each element, get the text and use .replace(" ","")

But is there an easier method or approach to this?

Upvotes: 0

Views: 2072

Answers (2)

Andy Turner
Andy Turner

Reputation: 140319

There is no easier way to do something to each elements in a list than to go through all elements in the list and do something to each element.

Use a ListIterator to iterate the list and update the values:

ListIterator<String> itr = list.listIterator();
while (itr.hasNext()) {
  itr.set(itr.next().replaceAll("\\s", ""));
}

Note that to replace all whitespace (not simply " "), you need to use a regular expression, as demonstrated here.

Upvotes: 2

GHajba
GHajba

Reputation: 3691

There is no such better option. One approach with Java 8 would be to map the elements of the list and then collect the result:

import static java.util.stream.Collectors.toList;
List<String> al = Arrays.asList("This is a ", "sentence", "\t with some", "\nwhite \n space ");
al.stream().map(s -> s.replaceAll("\\s", "")).forEach(System.out::println);
List<String> cleaned = al.stream().map(s -> s.replaceAll("\\s", "")).collect(toList());

Note that the \\s in the replaceAll function matches for every whitespace (tabs and linebreaks too) -- not only spaces and not on the first. The simple replace function replaces only the first occurrence of the pattern.

The result of the example would be following:

Thisisa
sentence
withsome
whitespace

Upvotes: 1

Related Questions