This question already has answers here:
How to concat string values in array list
                                
                                    (2个答案)
                                
                        
                2年前关闭。
            
        

我认为有人已经在问这个问题了,但仍然如此。

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

例:

我有

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


我需要做到

{"Hey how are you"}


是否存在诸如join或smth之类的命令?因为我尝试将另一个String值添加到同一索引,但它仅替换了它。

最佳答案

您可以为该解决方案使用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

08-18 08:42
查看更多