Java: Convert List to String

后端 未结 5 1486
春和景丽
春和景丽 2020-12-29 01:36

How can I convert List to String? E.g. If my List contains numbers 1 2 and 3 how can it be converted to String = \"1,

相关标签:
5条回答
  • 2020-12-29 01:50

    In vanilla Java 8 (streams) you can do

    // Given numberList is a List<Integer> of 1,2,3...
    
    String numberString = numberList.stream().map(String::valueOf)
        .collect(Collectors.joining(","));
    
    // numberString here is "1,2,3"
    
    0 讨论(0)
  • 2020-12-29 01:58

    One way would be:

    Iterate over list, add each item to StringBuffer (or) StringBuilder and do toString() at end.

    Example:

    StringBuilder strbul  = new StringBuilder();
         Iterator<Integer> iter = list.iterator();
         while(iter.hasNext())
         {
             strbul.append(iter.next());
            if(iter.hasNext()){
             strbul.append(",");
            }
         }
     strbul.toString();
    
    0 讨论(0)
  • 2020-12-29 01:58

    I think you may use simply List.toString() as below:

    List<Integer> intList = new ArrayList<Integer>();
    intList.add(1);
    intList.add(2);
    intList.add(3);
    
    
    String listString = intList.toString();
    System.out.println(listString); //<- this prints [1, 2, 3]
    

    If you don't want [] in the string, simply use the substring e.g.:

       listString = listString.substring(1, listString.length()-1); 
       System.out.println(listString); //<- this prints 1, 2, 3
    

    Please note: List.toString() uses AbstractCollection#toString method, which converts the list into String as above

    0 讨论(0)
  • 2020-12-29 01:58

    Just to add another (of many) options from a popular library (Apache Commons):

    import org.apache.commons.lang3.StringUtils;
    
    String joinedList = StringUtils.join(someList, ",");
    

    See documentation: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join-java.lang.Iterable-java.lang.String-


    An elegant option from others' comments (as of Java 8):

    String joinedList = someList.stream().map(String::valueOf).collect(Collectors.joining(","));
    
    0 讨论(0)
  • 2020-12-29 02:06

    With Guava:

    String s = Joiner.on(',').join(integerList);
    
    0 讨论(0)
提交回复
热议问题