Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List of Double to List of String?

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?

like image 788
Rasmus Avatar asked Jun 02 '11 11:06

Rasmus


People also ask

How do I turn a List into a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I convert a List to a string in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

How do I convert a List of strings to a List of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);


1 Answers

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();
        }
    });
like image 109
alpian Avatar answered Sep 24 '22 00:09

alpian