Java: Convert List to String

后端 未结 5 1513
春和景丽
春和景丽 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:58

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

    List intList = new ArrayList();
    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

提交回复
热议问题