数组列表。在一个索引中连接String值

时间:2017-11-28 22:31:27

标签: java arraylist

我认为有人已经问过这个问题但仍然存在。

我有随机字符串值的ArrayList,我需要将这些值放入另一个ArrayList,但只能放在一个索引中。

示例:

我有

{ "hey","how","are","you"} 

我需要做到

{"Hey how are you"} 

是否有像join或smth这样的命令?因为我尝试将另一个String值添加到同一个索引中,但它只替换了它。

5 个答案:

答案 0 :(得分:2)

您可以将StringJoiner用于该解决方案。

List<String> mainList = new ArrayList<>();  //The one to contain all Strings from yourList
List<String> yourList = Arrays.asList("Hey", "how", "are", "you");    //The list of Strings

StringJoiner joiner = new StringJoiner(" "); //Space as delimiter, strings will be separated with spaces
for (String s : yourlist) {
    joiner.add(s);
}
mainList.add(joiner.toString());    //Add the new concatenated String to your list, in a single string

答案 1 :(得分:2)

Java 8添加了一个StringJoiner类,它完全符合您的要求(以下代码在Java 9中):

    List<String> list = List.of("hey", "how", "are", "you");
    StringJoiner joiner = new StringJoiner(" ");
    list.forEach(str -> joiner.add(str));
    System.out.println(joiner.toString()); // hey how are you
    // and if you want the final result to be in a list
    // Java 9:
    list = List.of(joiner.toString());
    // anything before Java 9
    list = Arrays.asList(joiner.toString());

另一种(更简单)的方法(自Java 8起):

String.join(" ", list)

答案 2 :(得分:0)

使用StringBuilder加入多个字符串

StringBuilder sb = new StringBuilder();
listA.forEach(item -> sb.append(item));

listB.add(sb.toString());

答案 3 :(得分:0)

commons.lang3.StringUtils

StringUtils.join(Object array [],String separator)

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

答案 4 :(得分:0)

一个解决方案就像:

List<String> result = new ArrayList<>(Arrays.asList(myList.stream().collect(Collectors.joining(" "))));