Mark Lutton
Mark Lutton

Reputation: 7007

Converting Java Collection of some class to Collection of String

Assume a class (for instance URI) that is convertable to and from a String using the constructor and toString() method.

I have an ArrayList<URI> and I want to copy it to an ArrayList<String>, or the other way around.

Is there a utility function in the Java standard library that will do it? Something like:

java.util.collections.copy(urlArray,stringArray);

I know there are utility libraries that provide that function, but I don't want to add an unnecessary library.

I also know how to write such a function, but it's annoying to read code and find that someone has written functions that already exist in the standard library.

Upvotes: 5

Views: 5236

Answers (5)

Bill K
Bill K

Reputation: 62769

Try:

public ArrayList<String> convert(ArrayList<URI> source) {
    ArrayList<String> dest=new ArrayList<String>();

    for(URI uri : source)
        dest.add(source.toString());

   return dest;
}

Seriously, would a built-in API offer a lot to that?

Also, not very OO. the URI array should probably be wrapped in a class. The class might have a .asStrings() method.

Furthermore you'll probably find that you don't even need (or even want) the String collection version if you write your URI class correctly. You may just want a getAsString(int index) method, or a getStringIterator() method on your URI class, then you can pass your URI class in to whatever method you were going to pass your string collection to.

Upvotes: 0

Cowan
Cowan

Reputation: 37543

I know you don't want to add additional libraries, but for anyone who finds this from a search engine, in google-collections you might use:

List<String> strings = Lists.transform(uris, Functions.toStringFunction());

one way, and

List<String> uris = Lists.transform(strings, new Function<String, URI>() {
  public URI apply(String from) {
     try {
       return new URI(from);
     } catch (URISyntaxException e) {
       // whatever you need to do here
     }
  }
});

the other.

Upvotes: 5

rob
rob

Reputation: 6247

Since two types of collections may not be compatible, there is no built-in method for converting one typed collection to another typed collection.

Upvotes: 0

Eric
Eric

Reputation: 767

Have a look at commons-collections:

http://commons.apache.org/collections/

I believe that CollectionUtils has a transform method.

Upvotes: 2

Yishai
Yishai

Reputation: 91871

No, there is no standard JDK shortcut to do this.

Upvotes: 4

Related Questions