How to use Ruby style map in Java vector?

I have a feeling that Google can respond quickly if I know the Java terminology for what I want to do, but I do not do this, so in trust, I trust. :)

I have an Object s vector, and I want the array from String contain the string representation of each element in the vector generated by calling toString() for each element.

In Ruby (or Perl, or Python, or Scheme, or any of millions of other languages ​​using the map method) here, how would I do this:

 vector.map(&:to_s) do |string| # do stuff end 

How can I make an equivalent in Java? I would like to write something like this:

 Vector<Object> vector = ...; String[] strings = vector.map(somethingThatMagicallyCallsToString); 

Any ideas?

+4
source share
2 answers

If you're okay with Guava , you can use its transform function.

 Iterable<String> strings = Iterables.transform(vector, Functions.toStringFunction()); 

transform second argument is an instance of the Function interface. You will usually write your own implementations, but Guava provides toStringFunction() and several others.

+4
source

One approach could be:

 Vector<Object> vector = ...; ArrayList strings = new ArrayList(); for (Object obj : vector) { strings.add(obj.toString()); } return strings.toArray(new String[1]); 
+2
source

All Articles