字符串的 ArrayList 到单个字符串 [英] ArrayList of Strings to one single string
问题描述
我有一个字符串数组列表(数组列表中的每个单独元素只是一个没有空格的单词),我想获取每个元素并将每个下一个单词附加到字符串的末尾.
I have an array list of strings (each individual element in the array list is just a word with no white space) and I want to take each element and append each next word to the end of a string.
所以说数组列表有
element 0 = "hello"
element 1 = "world,"
element 2 = "how"
element 3 = "are"
element 4 = "you?"
我想创建一个名为句子的字符串,其中包含你好,你好吗?"
I want to make a string called sentence that contains "hello world, how are you?"
推荐答案
从 Java 8 开始,这已添加到标准 Java API 中:
As of Java 8, this has been added to the standard Java API:
String.join()
方法:
String.join()
methods:
String joined = String.join("/", "2014", "10", "28" ); // "2014/10/28"
List<String> list = Arrays.asList("foo", "bar", "baz");
joined = String.join(";", list); // "foo;bar;baz"
还添加了
StringJoiner
:
StringJoiner
is also added:
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"
另外,它是 nullsafe,我很欣赏.我的意思是,如果 StringJoiner
在 List
中遇到 null
,它不会抛出 NPE:
Plus, it's nullsafe, which I appreciate. By this, I mean if StringJoiner
encounters a null
in a List
, it won't throw a NPE:
@Test
public void showNullInStringJoiner() {
StringJoiner joinedErrors = new StringJoiner("|");
List<String> errorList = Arrays.asList("asdf", "bdfs", null, "das");
for (String desc : errorList) {
joinedErrors.add(desc);
}
assertEquals("asdf|bdfs|null|das", joinedErrors.toString());
}
这篇关于字符串的 ArrayList 到单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!