Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to trim() all elements in a List<String>? [duplicate]

Tags:

java

list

java-8

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!

like image 211
heez Avatar asked Apr 05 '16 15:04

heez


People also ask

How do I trim a string list?

The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Parameter: It does not accepts any parameter. Return Value: It does not returns any value.

How do I cut all elements in a list?

ForEach(x => x = x. Trim(). TrimStart().

What a trim () in string does?

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How do you trim whitespace from all elements in an array?

Method 3: Basic method using for loop: Use for loop to traverse each element of array and then use trim() function to remove all white space from array elements.


2 Answers

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);
like image 71
Cootri Avatar answered Sep 17 '22 12:09

Cootri


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

    final List<Object> result = arrayList.stream()
        .map(String::trim)
        .collect(Collectors.toList());
like image 21
Jonathan Schoreels Avatar answered Sep 19 '22 12:09

Jonathan Schoreels