How do I prefix a String to each element in an array of Strings?

21,022

Solution 1

Nope. Since it should be about a three-line function, you're probably better of just sticking with the one you coded.

Update

With Java 8, the syntax is simple enough I'm not even sure if it's worth creating a function for:

List<String> eatFoods = foodNames.stream()
    .map(s -> "eat an " + s)
    .collect(Collectors.toList());

Solution 2

Nothing like this exists in the java libraries. This isn't Lisp, so Arrays are not Lists, and a bunch of List oriented functions aren't already provided for you. That's partially due to Java's typing system, which would make it impractical to provide so many similar functions for all of the different types that can be used in a list-oriented manner.

public String[] prepend(String[] input, String prepend) {
   String[] output = new String[input.length];
   for (int index = 0; index < input.length; index++) {
      output[index] = "" + prepend + input[index];
   }
   return output;
}

Will do the trick for arrays, but there are also List interfaces, which include resizable ArrayLists, Vectors, Iterations, LinkedLists, and on, and on, and on.

Due to the particulars of object oriented programming, each one of these different implementations would have to implement "prepend(...)" which would put a heavy toll on anyone caring to implement a list of any kind. In Lisp, this isn't so because the function can be stored independently of an Object.

Share:
21,022
darksider
Author by

darksider

Updated on March 10, 2021

Comments

  • darksider
    darksider about 3 years

    I would like to know if there is, in Java, a function that can prefix a defined String to the beginning of every String of an array of Strings.

    For example,

    my_function({"apple", "orange", "ant"}, "eat an ")  would return {"eat an apple", "eat an orange", "eat an ant"}
    

    Currently, I coded this function, but I wonder if it already exists.

    • Karl-Bjørnar Øie
      Karl-Bjørnar Øie almost 13 years
      Don't think that such a function exists in the standard sdk.
    • Andreas Krueger
      Andreas Krueger almost 13 years
      This question seems half-baked. The above code example is no complete Java code, and what means "exists"? If it means part of Java SE, you could have easily have found out by inspecting the java.util package. I can hardly imagine of someone implementing this in a serious, published Java library, since this gimmick does not belong in a library. Also the method declaration public String[] myFunction(String prefix,String... items) might be more practical.
  • vadipp
    vadipp over 11 years
    Your function looks like it returns a new array, but actually it modifies the old one. In general, the solution by @StriplingWarrior is preferred.