20

I have a List<String>, potentially holding thousands of strings. I am implementing a validation method, which includes ensuring that there aren't any leading or trailing whitespaces in each string.

I'm currently iterating over the list, calling String.trim() for each String, and adding it to a new List<String> and reassigning back to the original list after:

List<String> trimmedStrings = new ArrayList<String)();
for(String s : originalStrings) {
  trimmedStrings.add(s.trim());
}

originalStrings = trimmedStrings;

I feel like there's a DRYer way to do this. Are there alternate, more efficient approaches here? Thanks!

Edit: Yes I am on Java 8, so Java 8 suggestions are welcome!

heez
  • 2,029
  • 3
  • 27
  • 39
  • 1
    The linked question talks about uppercasing each String but this is the same here for trimming: `originalStrings.replaceAll(String::trim);` – Tunaki Apr 05 '16 at 15:31
  • Unfortunately, no. Strings are immutable, which means you have to work with new String objects than the one already in the List. With specific List implementations you could remove an element and insert the trimmed object at the same position, that would save you the second ``List``. – f1sh Apr 05 '16 at 15:31

2 Answers2

54

In Java 8, you should use something like:

List<String> trimmedStrings = 
    originalStrings.stream().map(String::trim).collect(Collectors.toList());

also it is possible to use unary String::trim operator for elements of the initial list (untrimmed String instances will be overwritten) by calling this method:

originalStrings.replaceAll(String::trim);
Cootri
  • 3,806
  • 20
  • 30
  • 1
    Thanks Cootri. How does your solution differ from Tunaki's `originalStrings.replaceAll(String::trim)`? – heez Apr 05 '16 at 15:41
  • 3
    he modifies elements of the input list. So there is no need to declare new `trimmedStrings` list and waste more space. But the initial untrimmed `String` values will be lost – Cootri Apr 05 '16 at 15:43
  • 1
    You should suggest a Java 7 solution, here is one I put together: http://pastebin.com/sF3ixCq4 – Mr. Polywhirl Apr 05 '16 at 15:48
  • @Mr.Polywhirl Why? This question is tagged Java 8. There is no need to add more code for the fun of it. Especially that it introduces classes that do not exist like `CollectionUtil`. – Tunaki Apr 05 '16 at 16:03
  • @Tunaki: I simply added a suggestion. I only added the missing class... :( – Mr. Polywhirl Apr 05 '16 at 16:26
  • why does not foreach work ? for example, `list.foreach(str-> str = str.trim())` – Arun Gowda Jan 23 '18 at 16:45
  • 1
    I was working something more complex and your code helped Cootri. Thanks you. – Rakesh Narang Jul 05 '19 at 06:47
4

If you are on java-8, you can use :

    final List<Object> result = arrayList.stream()
        .map(String::trim)
        .collect(Collectors.toList());
Jonathan Schoreels
  • 1,660
  • 1
  • 12
  • 20