Joachim understood this correctly. People who say that you need to trim your lines before putting them on the first list also understood correctly.
In any case, if the latter is not an option for you, there may be an alternative approach: are you sure you will use all the trimmed lines? Or will you use only some of them, let's say, perhaps only the first five of them? Then it could be a bust to crop them all.
You can create a special implementation of List that will retain the original list, but will produce items trimmed. Here is what I mean:
public class ImmutableStringTrimmingList extends AbstractList<String> { private final List<String> stringList; public ImmutableStringTrimmingList(List<String> stringList) { this.stringList = stringList; } @Override public String get(int index) { return stringList.get(index).trim(); } @Override public int size() { return stringList.size(); } }
ImmutableStringTrimmingList stores the original list (therefore, any changes to this list will also be distributed here) and hand out String objects that are lazily trimmed. This can be useful if you do not want to do any unnecessary work, as it will only trim the lines requested by get() . It can also be adapted to cache the cropped object, so it does not have to retrieve it every time. But this is a practice for you if you find this class useful.
Or, if you are a Guava user, you can use Lists.transform() , which basically does the same, is also lazy.
List<String> trimmedList = Lists.transform(list, new Function<String, String>() { @Override public String apply(String input) { return input.trim(); } });
source share