4

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?

Josh Glover
  • 25,142
  • 27
  • 92
  • 129
  • 2
    As an orthogonal point, this *might* be useful info: http://stackoverflow.com/questions/1386275/why-java-vector-class-is-considered-obsolete-or-deprecated. Your best bet is to use an `ArrayList` (if possible). – Jits May 28 '11 at 12:50
  • It may also depend on the result you want to have. Do you need it to be `String[]` or would an iterator be sufficient? – Howard May 28 '11 at 12:56
  • @Howard: An iterator should be fine. – Josh Glover May 28 '11 at 16:37
  • @Jits: Thanks for the info on `ArrayList`; I wasn't aware of `Vector`'s unfortunate synchronisation behaviour. – Josh Glover May 28 '11 at 16:40

2 Answers2

4

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.

Samir Talwar
  • 14,220
  • 3
  • 41
  • 65
  • Awesome! This is exactly what I was after. Strange that they called it `transform`. ;) – Josh Glover May 28 '11 at 16:37
  • @Josh "Map" is overloaded, what with `java.util.Map` meaning something quite different. I think `transform` better describes it anyway, but it's not the most common name for it. – Samir Talwar May 28 '11 at 18:45
  • 1
    Yes, that's an unfortunate namespace collision. Lisps were calling the list transformation "map" long before Java was born, so I blame Bill Joy personally for this confusion. ;) – Josh Glover May 31 '11 at 04:14
2

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]);
Jits
  • 9,647
  • 1
  • 34
  • 27