Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 602
Mark Lutton Avatar asked Nov 11 '09 00:11

Mark Lutton


1 Answers

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.

like image 91
Cowan Avatar answered Sep 17 '22 14:09

Cowan