字符串的ArrayList为一个字符串 [英] ArrayList of Strings to one single string

查看:129
本文介绍了字符串的ArrayList为一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组列表(数组列表中的每个单独元素只是一个没有空格的单词),我想取每个元素并将每个下一个单词追加到字符串的末尾。

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?"

我想创建一个名为句子的字符串,其中包含hello world,你好吗?

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 列表中遇到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆