Saturday, 1 August 2015

Convert Collection into Comma Separated String


                            Convert Collection into Comma Separated String

while coding some module ,there comes a scenario where you need to convert your collection into comma separated string.
Suppose for example you need to pass list of strings to Stored procedure but your procedure argument accepts only varchar value.
in that case you need to convert your list of strings into comma separeted strings.


Below are some ways which you can implement.

1) Iterate over list elements,Concatenate each of the list elements and comma until last element  

 package com.ipaccess.nos.gui.module.config.wizard.changeProductClass;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class ListToString {  
   public static void main(String[] args) {  
    //Supoose this is your list containing integer {1,2,3,4}  
    List<Integer> numbers = new ArrayList<Integer>();  
    numbers.add(1);  
    numbers.add(2);  
    numbers.add(3);  
    numbers.add(4);  
    //StringBuilder to store comma separated string    
    StringBuilder commaSepString = new StringBuilder();  
    // iterate over list,append numbers and comma until last element    
    for (int i = 0; i < numbers.size(); i++) {  
      commaSepString.append(numbers.get(i));  
      if (i != numbers.size() - 1) {  
       commaSepString.append(", ");  
      }  
    }  
    System.out.println(commaSepString.toString());  
   }  
 }  


2) you can make use of google-collections.jar which has a utility class called Joiner

    String commaSepString=Joiner.on(",").join(numbers);
  
  To download this jar ,you can use this link 
http://www.java2s.com/Code/Jar/g/Downloadgooglecollections10jar.htm

3) Another way is you can use StringUtils class which has function called join.To make use of StringUtils class,you need to use common-lang3.jar

    String commaSepString=StringUtils.join(slist, ',');
  To download this jar ,you can use this link 
http://www.java2s.com/Code/Jar/c/Downloadcommonlang3jar.htm



Enjoy Learning.:)

No comments:

Post a Comment