如何连接数组列表中的字符串值 [英] How to concat string values in array list
本文介绍了如何连接数组列表中的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用 concat 一次打印所有数组列表值.
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).
推荐答案
请更喜欢 List
接口而不是 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屋!
查看全文