Link to home
Start Free TrialLog in
Avatar of srikotesh
srikotesh

asked on

how to convert list object into a string in java

Hi Experts,

I Want to get the list of names from the database
List<Object>names= ///getting from database
now i want convert this to String .
i have written the below code.
is there any to cut down my code.instead of using multiple for loops.
Thanks,

public String getNames(){
List<Object>names = dao.getDataFromDatabase()
for(Object object:names){
Object[] row = (Object[])object;
List<String>al = new ArrayList<>();
al.add((String) row[0]);
}
return convertlistToString(List<String>al)
}

Public String convertlistToString(List<String>al){
	StringBuilder commaSepValueBuilder = new StringBuilder();
    for ( int i = 0; i< al.size(); i++){
      //append the value into the builder
      commaSepValueBuilder.append(al.get(i));
       
      //if the value is not the last element of the list
      //then append the comma(,) as well
      if ( i != al.size()-1){
        commaSepValueBuilder.append(", ");
      }
    }
    commaSepValueBuilder.toString();

}

Open in new window

SOLUTION
Avatar of gurpsbassi
gurpsbassi
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CEHJ
return al.toString().replaceAll("\\[|\\]", "");

Open in new window


That's ok, but better if optimized to

return al.toString().replaceAll("^\\[|\\]$", "");

Open in new window

Avatar of srikotesh
srikotesh

ASKER

Hi Experts,

i am getting o/p along with array.
[sri, nivas, rao]
i dont want array here
i need output like
sri, nivas, rao
Have you tried the solution?
no
yes i am getting the expected response.

List<String> ids = new ArrayList<String>();
	ids.add("sri");
	ids.add("ni");
	ids.add("vas");
	ids.add("rap");

	// CSV format
	String csv = ids.toString().replace("[", "").replace("]", "")
	            .replace(", ", ",");
	System.out.println("csv is "+csv);

Open in new window


o/p:
sri,ni,vas,rap
String csv = ids.toString().replace("[", "").replace("]", "");
There's no reason to change the solution that gurpsbassi and i showed
Hi CEHJ,

i have verified that, list is coming with array

return al.toString().replaceAll("^\\[|\\]$", "");

[sri, ni, vas, rao, rrrr, rsss]

can u verify once how to modify this statement.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent
Answer by gurpsbassi really