如何为字符串数组中的每个元素添加字符串前缀?
问题描述:
我想知道在 Java 中是否有一个函数可以将定义的字符串前缀到字符串数组的每个字符串的开头.
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.
例如
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.
答
不.由于它应该是一个三行函数,因此您最好坚持使用您编写的代码.
Nope. Since it should be about a three-line function, you're probably better of just sticking with the one you coded.
Java 8 的语法非常简单,我什至不确定是否值得为以下对象创建函数:
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());