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,
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();
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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?
ASKER
no
ASKER
yes i am getting the expected response.
o/p:
sri,ni,vas,rap
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);
o/p:
sri,ni,vas,rap
ASKER
String csv = ids.toString().replace("[" , "").replace("]", "");
There's no reason to change the solution that gurpsbassi and i showed
ASKER
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Excellent
Answer by gurpsbassi really
That's ok, but better if optimized to
Open in new window