Search code examples
javacollectionsloops

How to modify, without any loop, a collections values to get a new collection?


How do I, without using any loop, modify the values in a collection to get a new collection with the modified values?

For example, I'm having a Collection<String> and want to surround all Strings by parentheses.

With a loop I would do this:

Iterable<String> collection = getCollection();
ArrayList<String> newCollection = new ArrayList<String>();    
for(String str : collection) 
    newCollection.add("(" + str + ")");

There has to be a more elegant solution.

EDIT: Use of third party utilities is allowed :)


Solution

  • no, there isn't. Using only JDK classes you cannot do it better. Check my second answer

    EDIT

    try google collection library Lists.trasform:

    List<String> out = Lists.transform(in, new Function<String, String>() {
    
        public String apply(String s) {
            return String.format("(%s)", s);
        }
    });