开发者

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.


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.


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


Have a look at commons-collections:

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

I believe that CollectionUtils has a transform method.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜