如何在数组列表中连接字符串值 [英] How to concat string values in array list

查看:105
本文介绍了如何在数组列表中连接字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用concat一次打印所有的arraylist值。

I need to print all arraylist values at a time using concat.

这是我的代码:

ArrayList<String> lst = new ArrayList<String>();
lst.add("hi");
lst.add("hello");
Iterator<String> itr = lst.iterator();
String result = null;

while(itr.hasNext()) {
   Object element = itr.next();
   result = element + " ";
}

System.out.println(result);

预期结果应为 hi hello

然而当前的输出是 hello (最后还有一个空格 )。

The current output however is hello (there is also a whitespace at the end).

推荐答案

请更喜欢列表界面 ArrayList 具体类型。假设您使用的是Java 8+,您可以使用 Stream Collectors.joining (以及 Arrays.asList )喜欢

Please prefer the List interface to the ArrayList concrete type. Assuming you are using Java 8+, you might use a Stream and Collectors.joining (and Arrays.asList) like

List<String> lst = Arrays.asList("hi", "hello");
String r = lst.stream().collect(Collectors.joining(" "));
System.out.println(r);

哪些输出

hi hello

按要求。

这篇关于如何在数组列表中连接字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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