[英]How to get String values from ArrayList and store them in a single string separated by commas, in Java 8?
I have an ArrayList with some Strings. 我有一个带有一些字符串的ArrayList。 I want to store that list of numbers from the ArrayList in a single string separated by a comma like the following.
我想将ArrayList中的数字列表存储在由逗号分隔的单个字符串中,如下所示。
String s = "350000000000050287,392156486833253181,350000000000060764"
This is my list: 这是我的清单:
List<String> e = new ArrayList<String>();
e.add("350000000000050287");
e.add("392156486833253181");
e.add("350000000000060764");
I have been trying to do it the following way: 我一直试图通过以下方式实现:
StringBuilder s = new StringBuilder();
for (String id : e){
s.append(id+",");
}
The only problem with this is that this adds a comma to the end and I do not want that.What would be the best way to this? 唯一的问题是,这会在最后添加一个逗号,我不希望这样。最好的方法是什么?
Thanks 谢谢
The easiest solution is to use String.join : 最简单的解决方案是使用String.join :
List<String> list = new ArrayList<String>();
list.add("11");
list.add("22");
list.add("33");
String joined = String.join(",", list);
System.out.println(joined);
//prints "11,22,33"
Note that this requires Java 8. 请注意,这需要Java 8。
However if you want to support older versions of Java, you could fix your code using an iterator: 但是,如果要支持旧版本的Java,可以使用迭代器修复代码:
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = list.iterator();
// First time (no delimiter):
if (iterator.hasNext()) {
sb.append(iterator.next());
// Other times (with delimiter):
while (iterator.hasNext()) {
sb.append(",");
sb.append(iterator.next());
}
}
Or simply use a boolean to determine the first time: 或者只是使用布尔值来确定第一次:
StringBuilder sb = new StringBuilder();
boolean firstTime = true;
for (String str : list) {
if (firstTime) {
firstTime = false;
} else {
sb.append(",");
}
sb.append(str);
}
But the latter should obviously be less performant than using an iterator comparing the generated bytecode per method. 但后者显然不如使用迭代器比较每个方法生成的字节码。 However, this might not be true as Tagir Valeev pointed out: this benchmark shows us that using a flag is more performant with a number of iterations starting from 10.
然而,正如Tagir Valeev指出的那样,这可能不是真的:这个基准测试向我们表明,使用一个标志从10开始进行多次迭代会更加高效 。
If anyone could explain why this is the case, I'd be glad to know. 如果有人能解释为什么会这样,我很高兴知道。
Upvote for Tim for that Java 8 solution ;) 为这个Java 8解决方案的Tim Upvote;)
If you are not using JDK 8 如果您不使用JDK 8
StringBuilder s = new StringBuilder();
for (String id : e){
s.append(id).append(",");
}
String result =s.toString().replaceAll(",$", "");
The regex I used ",$"
is to detect the last comma. 我使用
",$"
的正则表达式是检测最后一个逗号。
And also if you see, I'm replaced s.append(id +",");
如果你看到,我已经取代了
s.append(id +",");
with s.append(id).append(",");
with
s.append(id).append(",");
for better performance 为了更好的表现
You can take a boolean flag to check first iteration, if not first iteration append ","
before append id
. 您可以使用布尔标志来检查第一次迭代,如果不是第一次迭代,则在追加
id
之前追加","
。
This may solve your problem. 这可以解决您的问题。
boolean first = true;
for (String id : e){
if(!first)
s.append(",");
else
first = false;
s.append(id);
}
NOTE 注意
If you use Java8 then follow the solution of Tim. 如果您使用Java8,请遵循Tim的解决方案。
Try iterating through your list by checking if the current index is last value of list (e.size-1), if it is not the last value, then concatenate the string as normal with ",", if it is, then concatenate without ",". 尝试通过检查当前索引是列表的最后一个值(e.size-1)来迭代遍历列表,如果它不是最后一个值,则将该字符串与“,”连接起来,如果是,则连接而不连接“”。
List<String> e = new ArrayList<>(Arrays.asList("3333", "4444", "3333"));
StringBuilder s = new StringBuilder();
for (int i = 0; i < e.size(); i++) {
s.append(e.get(i)).append((i == e.size() - 1) ? "" : ",");
}
StringBuilder s = new StringBuilder();
for(int i = 0; i < e.size()-1; i++){
s.append(e.get(i)+",")
}
s.append(e.get(i))
Collectors.joining(",")
, work well in your case, example implementation: Collectors.joining(",")
在您的情况下运行良好,示例实现:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Solution {
public static void main(String[] args) {
List<String> e = new ArrayList<>();
e.add("350000000000050287");
e.add("392156486833253181");
e.add("350000000000060764");
System.out.println(e.stream().collect(Collectors.joining(",")));
}
}
Output: 输出:
350000000000050287,392156486833253181,350000000000060764
If we're talking about Java 8, how about: 如果我们谈论Java 8,那么:
Collection<String> e = asList("a", "b", "c");
String result = e.stream().collect(Collectors.joining(",")); // a,b,c
this method could be applied to any Collection
of strings, as well as String.join()
. 此方法可以应用于任何字符串
Collection
,以及String.join()
。
List<String> e = new ArrayList<String>();
e.add("350000000000050287");
e.add("392156486833253181");
e.add("350000000000060764");
Iterator iterator = e.iterator();
String s="";
int i = 1;
while (iterator.hasNext()) {
if (i == e.size()) {
s =s+iterator.next();
} else {
s =s+iterator.next()+",";
}
i++;
}
System.out.println(s);
350000000000050287,392156486833253181,350000000000060764
350000000000050287,392156486833253181,350000000000060764
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.