简体   繁体   中英

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 ?

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();
        }
    });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM