I have a feeling this is a question that Google could quickly answer if I knew the Java terminology for what I want to do, but I don’t, so in Stack Overflow I trust. 🙂
I have a vector of Objects, and I want an array of Strings containing the string representation of each element in the vector, as generated by calling toString() on each element.
In Ruby (or Perl, or Python, or Scheme, or any of the millions of other languages with a map method), here’s how I’d do it:
vector.map(&:to_s) do |string|
# do stuff
end
How can I do the equivalent in Java? I’d like to write something like this:
Vector<Object> vector = ...;
String[] strings = vector.map(somethingThatMagicallyCallsToString);
Any ideas?
If you’re OK bringing in Guava, you can use its
transformfunction.transform‘s second argument is an instance of theFunctioninterface. Usually you’ll write your own implementations of this, but Guava providestoStringFunction()and a few others.