简体   繁体   English

如何从ArrayList获取String值并将它们存储在Java 8中用逗号分隔的单个字符串中?

[英]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.

相关问题 如何从JAVA中的字符串数组列表中的单引号中创建逗号分隔的字符串 - how to create comma separated string in single quotes from arraylist of string in JAVA 如何从用逗号分隔的字符串中获取元素 - How to obtain elements from String separated by commas Java 如何从 ArrayList 存储字符串值<String>到一个 ArrayList<Object> 对象 - How to store String values from an ArrayList<String> to an ArrayList<Object> of Objects 如何使用Java为列表中的每个字符串添加或插入&#39;(单引号),其中字符串以逗号分隔 - How to add or insert ' (single quotes) for every string in a list in which strings are separated by commas using Java 如何从 String 中过滤掉 Unique 元素并将它们存储到 ArrayList - How filter out Unique elements from a String and store them into an ArrayList 如何使用Java Play中的MorphiaQuery从集合中获取所有_id值并将其存储在arraylist中 - How to get all _id values from a collection and store them in arraylist using MorphiaQuery in Java Play 如何从ArrayList获取值 <Hashtable<String, ArrayList<String> &gt;&gt; - how to get values from an ArrayList<Hashtable<String, ArrayList<String>>> 如何从ArrayList获取值<String[]> - How to get values from ArrayList<String[]> 如何从文本行读取多个String值并将其存储到String变量(java) - How to read a multiple String values from text line and store them to a String variable(java) 如何存储一个ArrayList <HashMap<String, String> &gt;具有单个Hashmap和多个Arraylist - How to store an a ArrayList<HashMap<String, String>> with a single Hashmap and multiple Arraylist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM