[英]How do I prefix a String to each element in an array of Strings?
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.我想知道在 Java 中是否有一个 function 可以将定义的字符串前缀到字符串数组的每个字符串的开头。
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.目前,我编码了这个 function,但我想知道它是否已经存在。
Nope.没有。 Since it should be about a three-line function, you're probably better of just sticking with the one you coded.
由于它应该是大约三行 function,因此您最好还是坚持使用您编写的那个。
With Java 8, the syntax is simple enough I'm not even sure if it's worth creating a function for:使用 Java 8,语法很简单,我什至不确定是否值得为:
List<String> eatFoods = foodNames.stream()
.map(s -> "eat an " + s)
.collect(Collectors.toList());
Nothing like this exists in the java libraries. java 库中没有这样的东西。 This isn't Lisp, so Arrays are not Lists, and a bunch of List oriented functions aren't already provided for you.
这不是 Lisp,所以 Arrays 不是列表,并且还没有为您提供一堆面向列表的功能。 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.
这部分是由于 Java 的类型系统,这使得为所有可以以面向列表的方式使用的不同类型提供如此多的类似函数是不切实际的。
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 ArrayList
s, Vector
s, Iteration
s, LinkedList
s, and on, and on, and on.可以为 arrays 解决问题,但也有
List
接口,其中包括可调整大小的ArrayList
、 Vector
、 Iteration
、 LinkedList
等等。
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.由于 object 面向编程的特殊性,这些不同的实现中的每一个都必须实现“prepend(...)”,这将对任何想要实现任何类型的列表的人造成沉重的负担。 In Lisp, this isn't so because the function can be stored independently of an Object.
在 Lisp 中,情况并非如此,因为 function 可以独立于 Object 存储。
How about something like...怎么样...之类的
public static String[] appendTo(String toAppend, String... appendees) {
for(int i=0;i<appendees.length;i++)
appendees[i] = toAppend + appendees[i];
return appendees;
}
String[] eating = appendTo("eat an ", "apple", "orange", "ant")
You could use a stream with a .concat()
method reference您可以使用带有
.concat()
方法参考的 stream
List<String> eatingFoods = foods.stream()
.map("eat an "::concat)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.