How to convert List of Double to List of String?

14,661

Solution 1

There are many ways to do this but here are two styles for you to choose from:

List<Double> ds = new ArrayList<Double>();
// fill ds with Doubles
List<String> strings = new ArrayList<String>();
for (Double d : ds) {
    // Apply formatting to the string if necessary
    strings.add(d.toString());
}

But a cooler way to do this is to use a modern collections API (my favourite is Guava) and do this in a more functional style:

List<String> strings = Lists.transform(ds, new Function<Double, String>() {
        @Override
        public String apply(Double from) {
            return from.toString();
        }
    });

Solution 2

You have to iterate over your double list and add to a new list of strings.

List<String> stringList = new LinkedList<String>();
for(Double d : YOUR_DOUBLE_LIST){
   stringList.add(d.toString());
}
return stringList;

Solution 3

List<Double> ds = new ArrayList<Double>();
// fill ds with Doubles
List<String> strings = ds.stream().map(op -> op.toString()).collect(Collectors.toList());

Solution 4

List<Double> doubleList = new ArrayList<Double>();
doubleList.add(1.1d);
doubleList.add(2.2d);
doubleList.add(3.3d);

List<String> listOfStrings = new ArrayList<String>();
for (Double d:doubleList)
     listOfStrings.add(d.toString());
Share:
14,661
Rasmus
Author by

Rasmus

Updated on June 17, 2022

Comments

  • Rasmus
    Rasmus almost 2 years

    This just might be too easy for all of you, but I am just learning and implementing Java in a project and am stuck with this.

    How to convert List of Double to List String?

  • Rasmus
    Rasmus almost 13 years
    Thanks I used the first method !
  • Rasmus
    Rasmus almost 13 years
    Thank Thomas! all of you have basically pointed to the same method .. thanks a tonne