How to use a Ruby-style map on a Java vector?
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 Object
s, and I want an array of String
s 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(somethingThat开发者_StackOverflow社区MagicallyCallsToString);
Any ideas?
If you're OK bringing in Guava, you can use its transform
function.
Iterable<String> strings = Iterables.transform(vector, Functions.toStringFunction());
transform
's second argument is an instance of the Function
interface. Usually you'll write your own implementations of this, but Guava provides toStringFunction()
and a few others.
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]);
精彩评论